python
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"<<<发送ip:{desp_ip},port:{desp_port},信息:{content}"
self.q.put(msg)
else:
break
def __del__(self):
self.udp.close()
class ChatHistory(Thread):
def __init__(self,q:Queue):
super().__init__()
self.q :Queue = q
def run(self):
while True:
data = self.q.get()
with open("./chathistory.txt",'a',encoding='utf-8') as f:
f.write(data)
f.write("\n")
def main():
udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp.bind(("127.0.0.1",650))
q = Queue()
#创建一个接受线程
recv_msg_thread =RecvUdp(udp,q)
#线程
recv_msg_thread.start()
#发送线程
send_msg_thread = SendUdp(udp,q)
send_msg_thread.start()
#quen
chat_thread =ChatHistory(q)
chat_thread.start()
main()