udp_聊天室

import socket


def send_socket(udp_socket, info_ip, info_post):
    info = input(">>>")
    udp_socket.sendto(info.encode("utf-8"), (info_ip, info_post))


def recv_socket(udp_socket):
    recv_msg = udp_socket.recvfrom(1024)
    recv_msga = recv_msg[0].decode("utf-8")
    recv_ip = recv_msg[1]
    print("来自%s的用户说:%s" % (str(recv_ip), recv_msga))


def main():
    # 1.创建套接字
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    # 2.绑定信息
    udp_socket.bind(("", 8080))
    # 输入对方信息
    print("欢迎来到XXX的聊天室")
    info_ip = input("请输入用户ip:")
    info_post = int(input("请输入用户端口:"))
    while True:
        print("*" * 50)
        info = input("请选择你的操作(1.发送 2.接收 0.退出):")
        if info == "0":
            print("*" * 50)
            udp_socket.close()
            break
        elif info == "1" or info == "结束发送":
            print("发送消息(输入“结束发送”结束)-------")
            while True:
                if info == "结束发送":
                    break
                else:
                    send_socket(udp_socket, info_ip, info_post)
        elif info == "2" or info == "结束接收":
            print("接收消息(输入“结束接收”结束)-------")
            while True:
                if info == "结束接收":
                    break
                else:
                    recv_socket(udp_socket)
        else:
            print("输入错误请重新输入:")

if __name__ == '__main__':
    main()



猜你喜欢

转载自blog.csdn.net/weixin_43693233/article/details/86212877