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()

你可能感兴趣的:(网络编程)