Python使用UDP实现简易聊天室

from socket import *
import threading


def send_data():
    while True:
        data = input('<<')  # 行首会一直有<< 等待输入
        udp_socket.sendto(data.encode('gbk'), (dest_ip, dest_port))


def receive_data():
    while True:
        content, addr = udp_socket.recvfrom(1024)
        print('\r>>%s:%s' % (content.decode('gbk'), addr[0]))  # 回到行首替换为 >>
        print('\r<<', end='')  # 回到行首替换为 <<


udp_socket = None
dest_ip = ''
dest_port = 0


def main():
    global udp_socket
    global dest_ip
    global dest_port
    dest_ip = input('请输入ip地址')
    dest_port = int(input('请输入端口号'))
    udp_socket = socket(AF_INET, SOCK_DGRAM)
    bind_addr = ('', 8899)
    udp_socket.bind(bind_addr)
    s_t = threading.Thread(target=send_data)
    r_t = threading.Thread(target=receive_data)
    r_t.start()
    s_t.start()
    r_t.join()
    s_t.join()


if __name__ == '__main__':
    main()
    udp_socket.close()

 

你可能感兴趣的:(python,每日总结)