UDP_socket 채팅 기능 구현

코드:

import socket
from threading import Thread


def send_data():
    #     
    while True:
        send_data = input()
        if send_data == "exit":
            break
        #   IP  
        ip_port = ("127.0.0.1", 9999)

        #     
        udp_socket.sendto(send_data.encode("gbk"), ip_port)  #   1:      2:  ip  (  )


def recv_data():
    #   IP  
    local_addr = ('', 60000)
    #     
    udp_socket.bind(local_addr)
    #     
    #     
    while True:
        recv_con = udp_socket.recvfrom(1024)  # 1024          ,       
        #  (b'\xc8\xfd\xcf\xdf\xb3\xc7\xca\xd0', ('192.168.1.4', 10000))
        # print(recv_data)
        recv_data = recv_con[0].decode('gbk')
        from_ip = recv_con[1][0]
        from_port = recv_con[1][1]
        #        
        print(from_ip+"    "+str(from_port)+":"+recv_data)

udp_socket = None

def main():

global udp_socket
#      
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

recv = Thread(target=recv_data)
send = Thread(target=send_data)
recv.start()
send.start()
recv.join()
send.join()

#      
udp_socket.close()


if __name__ == '__main__':
    main()

좋은 웹페이지 즐겨찾기