写一个两个人的聊天系统,可以实现双向聊天功能。
如果发送的是普通的文字就直接打印,如果发送的文字是’拜拜’就关闭连接,
如果是一个网络地址就获取数据(保存到文本文件中),如果是图片地址就下载图片到本地
只实现了发送‘拜拜’时能够中断连接和发送网络地址是能够下载打印网页数据,通过发送的图片地址将图片保存在本地暂时还没有实现。
服务器代码实现:
import socket
if __name__ == "__main__":
# 创建服务器套接字对象
server = socket.socket()
# 绑定ip地址及串口
server.bind(('10.7.181.98', 12345))
# 实现监听
server.listen(50)
# 保持服务器始终开启
while True:
# 接收客户端请求
conversation, address = server.accept()
while True:
message = input('>>>')
conversation.send(message.encode())
message_data = conversation.recv(1024)
print(message_data.decode(encoding='utf-8'))
# message_null = bytes()
# while message_data:
# message_null += message_data
# print(message_null)
# message_close = '拜拜'
# if message_close == message_null:
# conversation.close()
客户端代码实现:
import socket
import re
from requests import request
if __name__ == "__main__":
client = socket.socket()
client.connect(('10.7.181.98', 12345))
while True:
data = client.recv(1024)
data_re = re.match(r'http.*', data.decode(encoding='utf-8'))
if data_re:
url = data
response = request('GET', url)
print(type(response), response.text)
print(data.decode(encoding='utf-8'))
# data_null = bytes()
# while data:
# data_null += data
# print(data_null)
# if data_null == '拜拜':
# data.close()
message = input('>>>')
data.send(message.encode())
运行结果:
D:\Python\python.exe D:/千锋/课堂代码/UNIIT2/DAY19-计算机通信/homework.py
http://www.baidu.com
>>>
+++++++++++++++++++++++++++++++++++++++++++++++
D:\Python\python.exe D:/千锋/课堂代码/UNIIT2/DAY19-计算机通信/homework-client.py
<class 'requests.models.Response'> <!DOCTYPE html><html><head><meta http-equiv="........
http://www.baidu.com
网友评论