作业:
- 客户端和服务器聊天,可以一直聊天,直到一方发送’拜拜’。然后就可以和下一个人一直聊
服务器:
import socket
server = socket.socket()
server.bind(('10.7.187.55', 8888))
server.listen(100)
print('开始监听。')
while 1:
conversation, address = server.accept()
while 1:
get_data = conversation.recv(1024)
print('客户端:', get_data.decode('utf-8'))
if get_data.decode('utf-8') == '拜拜':
print('客户端已退出连接,等待下次客户端请求:', address)
break
send_data = input('服务器:')
conversation.send(send_data.encode('utf-8'))
if send_data == '拜拜':
print('已断开本次连接,等待下次客户端请求:')
break
客户端:
import socket
client = socket.socket()
client.connect(('10.7.187.55', 8888))
while 1:
send_data = input('客户端:')
client.send(send_data.encode('utf-8'))
if send_data == '拜拜':
print('已断开本次连接。')
break
get_data = client.recv(1024)
print('服务器:', get_data.decode('utf-8'))
if get_data.decode('utf-8') == '拜拜':
print('服务器已断开本次连接。')
break
2.客户端给服务器发送请求,请求成功后,客户端给服务发送‘1’,服务器就给客户端发送一张图片;客户端给服务发送‘2’,服务器就给客户端返回一个json文件中的内容;客户端给服务发送‘3’, 服务器返回’拜拜’,然后断开连接
服务器:
import socket
import json
server = socket.socket()
server.bind(('10.7.187.55', 8888))
server.listen(200)
print('开始监听:')
while 1:
conversation, adress = server.accept()
while 1:
get_data = conversation.recv(1024)
print('客户端:', get_data.decode('utf-8'))
if get_data.decode('utf-8') == '3':
send_data = '拜拜!'
conversation.send(send_data.encode('utf-8'))
print('当前客户端已断开连接。', adress)
break
elif get_data.decode('utf-8') == '1':
with open('王也.jpg', 'rb') as f:
send_data = f.read()
conversation.send(send_data)
print('已发送图片。')
elif get_data.decode('utf-8') == '2':
with open('files/测试文件.json', 'r', encoding='utf-8') as f:
content = json.load(f)
conversation.send(str(content).encode('utf-8'))
print('已发送文件。')
客户端:
import socket
client = socket.socket()
client.connect(('10.7.187.55', 8888))
while 1:
send_data = input('客户端:')
client.send(send_data.encode('utf-8'))
if send_data == '3':
print('已退出连接。')
break
elif send_data == '1':
content = bytes()
while 1:
get_data = client.recv(1024)
content += get_data
print(len(get_data))
# if len(get_data) == 39:
if len(get_data) < 1024:
break
with open('接收文件/图片1.jpg', 'bw') as f:
f.write(content)
print('接收图片成功。')
elif send_data == '2':
get_data = client.recv(1024)
print('服务器:', get_data.decode())