Python TCPServer 多线程多客户端通信的实现
作者:东南飘雪 时间:2021-07-05 22:33:00
最简单、原始的TCP通信demo
服务端Http请求:
import socket
# 创建一个servicesocke
serviceSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 给服务器绑定地址(ip地址,端口号)
serviceSocket.bind(("192.168.171.1", 80))
print("等待客户端接入")
# sock 是客户端的socket信息
# addr 是客户端的地址(ip,端口)
sock, addr = serviceSocket.accept()
print(f"sock from client:{sock}")
print(f"addr of client:{addr}")
while True:
# 接收客户端的请求
recvData = sock.recv(1024)
print("客户端说:%s" % (recvData.decode("utf-8")))
sendData = input("服务器说:")
# 发送(回复)数据给客户端
sock.send(sendData.encode("utf-8"))
客户端Http请求:
import socket
# 创建客户端socket
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 连接服务器
clientSocket.connect(("192.168.171.1", 80))
while True:
# 发送消息给服务器
sendData = input("客户端说:")
if sendData == "bye":
clientSocket.send(sendData.encode("utf-8")) # 编码:将数据装换成二进制形式
break
clientSocket.send(sendData.encode("utf-8"))
recvData = clientSocket.recv(1024)
print("服务器说:%s" % (recvData.decode("utf-8"))) # 解码:将二进制转换成字符
1、在TCP中,客户端的实现流程:
创建客户端的socket对象建立与服务器之间的联系发送请求接收数据关闭连接
2、服务端的实现流程:
创建服务端的socket对象绑定服务端的地址设置 * 等待客户端的连接接收客户端的请求返回处理的结果到客户端
ThreadingTCPServer 多线程多客户端通信自动重连demo
socketserver继承图:
TCPServer
# from socketserver import TCPServer, BaseRequestHandler, ThreadingTCPServer
from socketserver import TCPServer, StreamRequestHandler, ThreadingMixIn
import traceback
# class MyBaseRequestHandler(BaseRequestHandler):
class MyBaseRequestHandler(StreamRequestHandler):
def handle(self):
self.addr = self.request.getpeername()
self.server.users[self.addr[1]] = self.request
message = "IP " + self.addr[0] + ":" + str(self.addr[1]) + " Connected..."
print(message)
while True:
try:
data = self.request.recv(1024).decode('UTF-8', 'ignore').strip()
print(f'receive from {self.client_address}:{data}')
back_data = (f"response\"" + data + "\":\n").encode("utf8")
self.request.sendall(back_data)
except:
traceback.print_exc()
break
# 源码:class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
# 从ThreadingMixIn和TCPServer继承,实现多线程
class MyThreadingTCPServer(ThreadingMixIn, TCPServer):
def __init__(self, server_address, RequestHandlerClass):
TCPServer.__init__(self, server_address, RequestHandlerClass)
self.users = {}
class MyTCPserver():
def __init__(self, server_addr='192.168.1.109', server_port=23):
self.server_address = server_addr
self.server_port = server_port
self.server_tuple = (self.server_address, self.server_port)
def run(self):
# server = TCPServer(self.server_tuple, MyBaseRequestHandler)
server = MyThreadingTCPServer(self.server_tuple, MyBaseRequestHandler)
server.serve_forever()
if __name__ == '__main__':
myserver = MyTCPserver()
myserver.run()
在telnet 下开启开启两个客户端,本电脑的IP为192.168.1.109,开两个客户端后,TCPServer的终端出现同一个IP但是不同端口的连接:
TCPClient
import socket
import time
class MyClient:
host = '192.168.1.109'
port = 23
bufsiz = 1024
addr = None
skt = None
def __init__(self, host=None, port=None):
if host != None:
self.host = host
if port != None:
self.port = port
if self.addr == None:
self.addr = (self.host, self.port)
self.doConnection()
def doConnection(self):
try:
self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
print(self.addr)
self.skt.connect(self.addr)
except:
pass
def run(self):
while True:
try:
_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.skt.sendall(f'{_time}:i am clent1 '.encode('utf-8'))
data = self.skt.recv(self.bufsiz)
print(data.decode('utf-8', 'ignore'))
if not data:
break
print(data.strip())
time.sleep(5)
except socket.error:
print('socket error, reconnection') # 自动重连
time.sleep(3)
self.doConnection()
except:
print('other error')
self.skt.close()
myclient = MyClient()
myclient.run()
上面用的是telnet工具来作为客户端,这里是用代码实现模拟的客户端。
来源:https://blog.csdn.net/qq_31362767/article/details/103758119
标签:Python,TCPServer,通信
0
投稿
猜你喜欢
Keras之自定义损失(loss)函数用法说明
2023-09-24 12:12:15
Go语言高效编程的3个技巧总结
2024-02-03 02:52:38
Python松散正则表达式用法分析
2021-03-12 02:51:36
Python3 能振兴 Python的原因分析
2021-01-11 06:44:12
insert select与select into 的用法使用说明
2012-01-05 18:47:58
python判定文件目录是否存在及创建多层目录
2022-08-12 09:39:03
Python OpenCV视频截取并保存实现代码
2023-01-05 06:04:21
SQL Server特殊磁带备份及恢复设计
2009-01-21 14:39:00
网页特效文字之—银箔字
2013-08-07 00:21:39
利用Python写一个爬妹子的爬虫
2021-07-22 12:44:51
JS常见简单正则表达式验证功能小结【手机,地址,企业税号,金额,身份证等】
2024-04-19 10:15:32
学点简单的Django之第一个Django程序的实现
2021-03-23 05:10:59
python把一个字符串切开的实例方法
2022-07-10 21:52:17
Python生成ubuntu apt镜像地址实现
2023-10-13 04:39:29
chatGPT deBug解决管理员登入服务器返回401问题
2022-08-07 06:38:09
MySQL分库分表的几种方式
2024-01-22 05:25:36
在Python中使用SimpleParse模块进行解析的教程
2021-04-11 12:17:53
Python中面向对象你应该知道的一下知识
2022-01-31 11:35:47
DDL、DML和DCL的区别与理解
2024-01-23 23:08:01
python调用文件时找不到相对路径的解决方案
2021-08-21 14:38:24