天天看點

6.1UDP-多線程聊天器

#coding:utf-8
import socket
import threading

def recv_msg(udp_socket):
    while True:
        recv_data = udp_socket.recv(1024)
        print('recv_data')

def send_msg(udp_socket, dest_id, dest_port):
    while True:
        send_data = input('請輸入要發送的消息:')
        udp_socket.sendto(send_data.encode('utf-8'), (dest_id, dest_port))

def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind(('', 8080))

    dest_ip = input('請輸入對方ip:')
    dest_port = int(input('請輸入對方port:'))

    t_recv = threading.Thread(target=recv_msg, args=(udp_socket,))
    t_send = threading.Thread(target=send_msg, args=(udp_socket, dest_ip, dest_port))

    t_recv.start()
    t_send.start()


if __name__ == '__main__':
    main()