Python 简单的聊天室

import socket
import threading


def send_msg(udp_socket):
    ip_address = input("请输入接收方的ip地址:")
    ip_port = input("请输入接收方的端口号:")
    content = input("请输入要发送的内容:")
    udp_socket.sendto(content.encode("gbk"), (ip_address, int(ip_port)))


def recv_msg(udp_socket):
    while True:
        content_data, ip = udp_socket.recvfrom(1024)
        print(content_data.decode("gbk"))


def main():
    # 创建套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 绑定端口
    ip_address = ("", 8888)
    udp_socket.bind(ip_address)
    # 创建子线程 单独接收用户发送的信息
    thread_recvmsg=threading.Thread(target=recv_msg,args=(udp_socket, ))
    # 设置守护线程
    thread_recvmsg.setDaemon(True)
    thread_recvmsg.start()
    # 循环 -》打印菜单
    while True:
        print("************************************")
        print("************* 1、发送信息 ************")
        # print("************* 2、接受信息 ************")
        print("************* 2、退出系统 ************")
        print("************************************")
        condition = int(input("请输入需要的操作:"))
        if condition == 1:
            print("您选择了发送信息")
            send_msg(udp_socket)
        # elif condition == 2:
        #     print("您选择了接受信息")
        #     recv_msg(udp_socket)
        elif condition == 2:
            break
        else:
            print("请输入1至3的数字")

    # 关闭套接字
    udp_socket.close()
    exit(1)


main()
原文地址:https://www.cnblogs.com/lautung/p/13861880.html