python使用socket模块实现TCP高并发任务
from threading import Thread import socket class HandelParse(Thread): def __init__(self,socket_obj): super().__init__() self.socket_obj = socket_obj def run(self): while True: recv_msg = self.socket_obj.recv(1024) if len(recv_msg)!=0: print(recv_msg.decode("utf-8")) self.socket_obj.send(recv_msg) #再次原路发回去。注tcp用send方法,udp用sendto方法 else: self.socket_obj.close() break class TcpServer(Thread): def __init__(self): super().__init__() self.tcp_sercer = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.tcp_sercer.bind(("",7878)) self.tcp_sercer.listen(128) #设置监听数量 def run(self): while True: msg,client_info = self.tcp_sercer.accept() #等待连接 #创建子线程,实现多并发 handel_data_thread = HandelParse(msg) handel_data_thread.start() def __del__(self): self.tcp_sercer.close() if __name__ == '__main__': tcp = TcpServer() tcp.start()
使用网络调试工具测试。同时开通3 个调试助手软件进行连接。截图如下:
网络调试工具下载地址:
https://www.onlinedown.net/soft/971066.htm
多线程实socket编程
from threading import Thread from queue import Queue import socket class RecvUdp(Thread): def __init__(self,udp:socket.socket,q:Queue): super().__init__() self.udp = udp self.q: Queue = q def run(self): while True: msg,client_info = self.udp.recvfrom(1024) contect=f'>>>ip:{client_info[0]},port:{client_info[1]} 内容:{msg.decode("utf-8")}' self.q.put(contect) def __del__(self): self.udp.close() class SendUdp(Thread): def __init__(self,udp:socket.socket,q): super().__init__() self.udp = udp self.q: Queue = q def run(self): while True: desp_ip = input("请输入对方ip") desp_port = int(input("请输入对方端口:")) while True: content = input("请输入内容") if content : self.udp.sendto(content.encode("utf-8"),(desp_ip,desp_port)) msg = f"
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。