- 写一个两个人的聊天系统,可以实现双向聊天功能。
如果发送的是普通的文字就直接打印,如果发送的文字是’拜拜’就关闭连接,
如果是一个网络地址就获取数据(保存到文本文件中),如果是图片地址就下载图片到本地
server代码
import re
import socket
from requests import request
#1.创建服务器
server = socket.socket()
# 绑定地址
server.bind(('10.7.181.86',8060))
# 3.监听
server.listen(50)
# 保持服务器不关闭
while True:
conversation, addr = server.accept()
# 让客户端和服务器一直处于连接状态
while True:
# 发送消息
message = input('>>>')
conversation.send(message.encode())
if message == '拜拜':
break
if re.fullmatch(r'./S+./S+',message):
with open(message, 'rb') as f:
data = f.read()
conversation.send(data)
# 接收消息
message_data = conversation.recv(1024)
print(message_data.decode(encoding='utf-8'))
if message_data.decode(encoding='utf-8') == '拜拜':
break
if re.fullmatch(r'https://\S+', message_data.decode(encoding='utf-8')):
response = request('GET', message_data.decode(encoding='utf-8'))
text = response.text
with open('./text.txt','w',encoding='utf-8') as f:
f.write(text)
if re.fullmatch(r'./S+./S+', message_data):
with open('./image.png', 'wb') as f:
f.write(message_data)
break
# with open('./TCP.png', 'rb') as f:
# data = f.read()
# conversation.send(data)
conversation.close()
client代码
import socket
import re
from requests import request
# 1.创建套接字对象
client = socket.socket()
# 2.连接服务器
client.connect(('10.7.181.86',8060))
while True:
# 接收消息
data = client.recv(1024)
print(data.decode(encoding = 'utf-8'))
if data.decode(encoding = 'utf-8') == '拜拜':
break
if re.fullmatch(r'https://\S+',data.decode(encoding = 'utf-8')):
response = request('GET', data.decode(encoding = 'utf-8'))
text = response.text
with open('./text.txt', 'w',encoding='utf-8') as f:
f.write(text)
if re.fullmatch(r'./S+./S+', data.decode(encoding = 'utf-8')):
with open('./image.png', 'wb') as f:
f.write(data.decode(encoding = 'utf-8'))
# 发送消息
message = input('>>>')
client.send(message.encode(encoding='utf-8'))
if message == '拜拜':
break
if re.fullmatch(r'./S+./S+', message):
with open(message, 'rb') as f:
data = f.read()
client.send(data)
client.close()
网友评论