UDP实现多线程聊天
2021-02-18 03:18
标签:ram __name__ mamicode 聊天 decode data input rom img UDP实现多线程聊天 标签:ram __name__ mamicode 聊天 decode data input rom img 原文地址:https://www.cnblogs.com/monsterhy123/p/12694236.html 1 from socket import *
2 from threading import Thread
3 udp_socket = socket(AF_INET,SOCK_DGRAM)
4 #绑定端口
5 udp_socket.bind((‘‘,8989))
6
7 #不停接收
8 def recv_data():
9 while True:
10 recv_msg = udp_socket.recvfrom(1024)
11 print(‘>>%s:%s‘%(recv_msg[1],recv_msg[0].decode(‘gb2312‘)))
12
13 #不停发送
14 def sent_data():
15 while True:
16 data = input(‘‘)
17 addr = (‘192.168.0.107‘,8080)
18 udp_socket.sendto(data.encode(‘gb2312‘),addr)
19
20 if __name__ == ‘__main__‘:
21 #创建两个线程
22 t1 = Thread(target=sent_data)
23 t2 = Thread(target=recv_data)
24 t1.start()
25 t2.start()
26 t1.join()
27 t2.join()