# 服务端
import socket
import struct
import json
from threading import Thread
server = socket.socket()
server.bind(
('127.0.0.1', 9608)
)
server.listen(5)
def my_server(conn):
while True:
try:
headers = conn.recv(4)
if not headers:
continue
data_len = struct.unpack('i', headers)[0]
bytes_data = conn.recv(data_len)
back_dic = json.loads(bytes_data.decode('utf-8'))
if back_dic['msg'] == 'q':
break
print(f'{back_dic["name"]}:{back_dic["msg"]}')
msg1 = back_dic["msg"]
msg = msg1.upper()
to_dic = {'name': 'logan', 'msg': msg}
json_dic = json.dumps(to_dic)
bytes_dic = json_dic.encode('utf-8')
send_dic = struct.pack('i', len(bytes_dic))
conn.send(send_dic)
conn.send(bytes_dic)
except Exception as e:
print(e)
break
if __name__ == '__main__':
while True:
conn, addr = server.accept()
t = Thread(target=my_server, args=(conn,))
t.start()
# 客户端
import socket
import struct
import json
client = socket.socket()
client.connect(
('127.0.0.1', 9608)
)
while True:
try:
msg = input('发送内容:')
if msg == 'q':
break
dic = {'name': '用户1', 'msg': msg}
bytes_dic = json.dumps(dic)
send_dic = bytes_dic.encode('utf-8')
send_len = struct.pack('i', len(send_dic))
client.send(send_len)
client.send(send_dic)
headers = client.recv(4)
data_len = struct.unpack('i', headers)[0]
bytes_data = client.recv(data_len)
back_dic = json.loads(bytes_data.decode('utf-8'))
print(f'{back_dic["name"]}:{back_dic["msg"]}')
except Exception as e:
print(e)
break
client.close()