day18 网络编程作业
2018-11-28 本文已影响0人
遇见那天的雨真大
- 客户端和服务器聊天,可以一直聊天,直到一方发送’拜拜’。然后就可以和下一个人一直聊
#服务器端:
import socket
serve = socket.socket()
serve.bind(("10.7.187.128",9092))
serve.listen(1024)
print("开始监听")
while True:
conversation,addr = serve.accept()
while True:
data = conversation.recv(1024)
print("客户端:",data.decode("utf-8"))
if data.decode("utf-8") == "拜拜":
conversation.send("拜拜".encode(encoding="utf-8"))
print("下一会话者接听")
break
message = input("输入回话内容:")
conversation.send(message.encode(encoding="utf-8"))
if message == "拜拜":
print("下一会话者接听")
break
conversation.close()
#客户端:
import socket
client = socket.socket()
client.connect(("10.7.187.128",9092))
while True:
message = input("输入内容:")
client.send(message.encode(encoding="utf-8"))
if message == "拜拜":
print("断开会话连接")
break
data = client.recv(1024)
print("服务器:",data.decode("utf-8"))
if data.decode("utf-8") == "拜拜":
client.send("拜拜".encode(encoding="utf-8"))
break
client.close()
2.客户端给服务器发送请求,请求成功后,客户端给服务发送‘1’,服务器就给客户端发送一张图片;客户端给服务发送‘2’,服务器就给客户端返回一个json文件中的内容;客户端给服务发送‘3’, 服务器返回’拜拜’,然后断开连接
服务器:
import socket
serve = socket.socket()
serve.bind(("10.7.187.128",9096))
serve.listen(1024)
print("开始监听")
while True:
conversation,addr = serve.accept()
message = "请输入编号1:获取图片;2:获取json文件;3:拜拜"
conversation.send(message.encode(encoding="utf-8"))
data = conversation.recv(1024)
print("客户端:", data.decode("utf-8"))
while True:
data = conversation.recv(1024)
print("客户端:",data.decode("utf-8"))
if data.decode("utf-8") =="1":
with open("-4d29fda630106db2.jpg","rb") as f:
content = f.read()
conversation.send(content)
elif data.decode("utf-8") == "2":
with open("home.json","rb") as f:
content = f.read()
conversation.send(content)
elif data.decode("utf-8") == "3":
conversation.send("拜拜".encode(encoding="utf-8"))
else:
message = "请输入编号1:获取图片;2:获取json文件;3:拜拜"
conversation.send(message.encode(encoding="utf-8"))
conversation.close()
客户端:
import socket
client = socket.socket()
client.connect(("10.7.187.128",9096))
message = "我要请求"
client.send(message.encode(encoding="utf-8"))
while True:
re_data = client.recv(1024)
print("服务器:",re_data.decode("utf-8"))
message = input("输入内容:")
client.send(message.encode(encoding="utf-8"))
data1 = bytes()
if message == "1":
while True:
data = client.recv(1024)
data1 += data
if not data:
break
print("数据接收完了")
with open("回复1图片.jpg","wb") as f:
f.write(data1)
elif message == "2":
while True:
data = client.recv(1024)
data1 += data
if not data:
break
print("数据接收完了")
with open("new_home.json","w",encoding="utf-8") as f:
f.write(data1)
elif message == "3":
break
else:
print("输入有误,请重新请求")
break