day 29作业

服务端

import struct
import socket
import json
from multiprocessing import Process


def run(conn, addr):
    print(f'用户{addr}已连接')
    while True:
        try:
            data = conn.recv(4)
            conn.sendto(data,addr)
            data_len = struct.unpack('i', data)[0]

            data = conn.recv(data_len)
            conn.sendto(data,addr)
            data = json.loads(data)
            print(f'用户{addr}:\n{data}')
         except Exception as e:
            print(e)
            break
        
        
if __name__ == '__main__':
    server = socket.socket()
    server.bind(('127.0.0.1', 9527))
    server.listen(5)
    while True:
        conn, addr = server.accept()
        p = Process(target=run, args=(conn, addr))
        p.start()

客户端

import socket
import struct
import json




client = socket.socket()
client.connect(('127.0.0.1', 9527))
while True:


        dic = input()

        dic_beats = json.dumps(dic).encode('utf8')

        dic_len = struct.pack('i', len(dic_beats))

        client.send(dic_len)
        client.send(dic_beats)
        data_len =struct.unpack('i',client.recv(4))[0]
        data_beats = client.recv(data_len)
        data = json.loads(data_beats)
        print(data)

你可能感兴趣的:(day 29作业)