簡體   English   中英

可以使用 Python 中的 Pickle 和套接字模塊將數據對象從客戶端發送到服務器嗎?

[英]Can send data objects from client to server using the Pickle and socket modules in Python?

我希望我的客戶端程序將對象發送到服務器。 通過搜索互聯網,在所有示例中,我都看到數據對象是由服務器發送到客戶端的,但我想做相反的事情。 下面我分享客戶端代碼和服務器代碼。 我已經能夠修改套接字客戶端代碼,但我在修改服務器代碼時遇到了困難。 因為,我是 python 編程的新手,而且我正處於最后期限,非常感謝您的幫助。

以下是代碼:

服務器代碼::

import socket



def server_program():

    # get the hostname
    host = socket.gethostname()
    port = 5000  # initiate port no above 1024
    server_socket = socket.socket()  # get instance
    # look closely. The bind() function takes tuple as argument
    server_socket.bind((host, port))  # bind host address and port together

    # configure how many client the server can listen simultaneously
    server_socket.listen(2)
    conn, address = server_socket.accept()  # accept new connection
    print("Connection from: " + str(address))
    while True:
        # receive data stream. it won't accept data packet greater than 1024 bytes
        data = conn.recv(1024).decode()
        if not data:
            # if data is not received break
            break
        print("from connected user: " + str(data))
        data = input(' -> ')
        conn.send(data.encode())  # send data to the client

    conn.close()  # close the connection


if __name__ == '__main__':
    server_program()

這是用pickle修改的客戶端代碼::

import socket
import pickle


def client_program():
    host = socket.gethostname()  # as both code is running on same pc
    port = 5000  # socket server port number

    client_socket = socket.socket()  # instantiate
    client_socket.connect((host, port))  # connect to the server

    message = input(" -> ")  # take input

    while message.lower().strip() != 'bye':
        client_socket.send(message.encode())  # send message
        #data = client_socket.recv(1024).decode()  # receive response

        #print('Received from server: ' + data)  # show in terminal

        wastebin_attr = {1:"Wastebin_serial_number", 2:"Wastebin_type", 3:"Status" , 4:"Action", 5:"Zone", 6:"Latitude", 7:"Longitude"}
        mssg = pickle.dumps(wastebin_attr)
        print("from connected user: " + mssg)
        message = input(" -> ")  # again take input

    client_socket.close()  # close the connection


if __name__ == '__main__':
    client_program()

使用 pickle 模塊將數據從客戶端發送到服務器:

data = pickle.dumps(data)
client_socket.send(data)

要在服務器端接收數據,請使用:

data = conn.recv(1024)
data = pickle.loads(data)

您還可以通過切換 client_socket 和 conn 部分來使用它從服務器發送到客戶端

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM