多线程对话
from socket import *
from threading import Thread
udp_socket = socket(AF_INET, SOCK_DGRAM)
udp_socket.bind(('192.168.2.30', 5001))
def send(sock, msg, ip, port):
sock.sendto(msg.encode('utf-8'), (ip, port))
def recv(sock):
while True:
recv_data = udp_socket.recvfrom(1024)
data = recv_data[0].decode()
src_ip = recv_data[1][0]
src_port = recv_data[1][1]
print('\nRecive msg from {}-{}: {}'.format(src_ip, src_port, data))
if __name__ == '__main__':
t_recv = Thread(target=recv, args=(udp_socket, ))
t_recv.start()
while True:
data = input('[5001] Send message [ip port data]: ')
if len(data) <= 0:
continue
ip, port, msg = data.split()
t_send = Thread(target=send, args=(udp_socket, msg, ip, int(port)))
t_send.start()
执行效果
[root@Da scripts]# python35 socket_udp_4_c1.py
[5001] Send message [ip port data]: 192.168.2.30 5002 yo
[5001] Send message [ip port data]: 192.168.2.30 5002 yoo
[5001] Send message [ip port data]: 192.168.2.30 5002 yooo
[5001] Send message [ip port data]: 192.168.2.30 5002 yoooo
[root@Da scripts]# python35 socket_udp_4_c.py
[5002] Send message [ip port data]: 192.168.2.30 5001 da
[5002] Send message [ip port data]: 192.168.2.30 5001 da
[5002] Send message [ip port data]: 192.168.2.30 5001 da
[5002] Send message [ip port data]:
Recive msg from 192.168.2.30-5001: yo
Recive msg from 192.168.2.30-5001: yoo
Recive msg from 192.168.2.30-5001: yooo
Recive msg from 192.168.2.30-5001: yoooo