- 客户端和服务器聊天,可以一直聊天,直到一方发送’拜拜’。然后就可以和下一个人一直聊
服务器端
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('10.7.187.58', 8083))
server.listen(312)
while True:
conversation, addr = server.accept()
while True:
re_data = conversation.recv(1024)
print('客户端:', re_data.decode('utf-8'))
message = input('服务器')
conversation.send(message.encode('utf-8'))
if re_data.decode('utf-8') == '拜拜':
break
客户端
import socket
client = socket.socket()
client.connect(('10.7.187.58', 8083))
while True:
message = input('客户端')
client.send(message.encode('utf-8'))
data = client.recv(1024)
print('服务器:', data.decode('utf-8'))
if message == '拜拜':
break
2.客户端给服务器发送请求,请求成功后,客户端给服务发送‘1’,服务器就给客户端发送一张图片;客户端给服务发送‘2’,服务器就给客户端返回一个json文件中的内容;客户端给服务发送‘3’, 服务器返回’拜拜’,然后断开连接
服务器
import socket
import json
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('10.7.187.58', 8083))
server.listen(312)
while True:
conversation, addr = server.accept()
while True:
re_data = conversation.recv(1024)
print('客户端:', re_data.decode('utf-8'))
if re_data.decode('utf-8') == '1':
with open('王爷.jpg', 'rb') as f:
message = f.read()
conversation.send(message)
break
elif re_data.decode('utf-8') == '2':
with open('1.json', encoding='utf-8') as f:
message = json.load(f)
conversation.send(str(message).encode('utf-8'))
if re_data.decode('utf-8') == '3':
conversation.send('拜拜'.encode('utf-8'))
break
conversation.close()
客户端
import socket
import json
client = socket.socket()
client.connect(('10.7.187.58', 8083))
byte = bytes()
while True:
message = input('客户端')
client.send(message.encode('utf-8'))
if message == '1':
while True:
data = client.recv(1024)
byte += data
if not data:
break
with open('new2.jpg', 'bw') as f:
f.write(byte)
break
elif message == '2':
data = client.recv(1024)
with open('new1.json', 'w', encoding='utf-8') as f:
json.dump(data.decode('utf-8'), f)
with open('new1.json', encoding='utf-8') as f:
print(f.read())
else:
print((client.recv(1024)).decode('utf-8'))
break
client.close()