zoukankan      html  css  js  c++  java
  • 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()
    
  • 相关阅读:
    使用jQuery实现伪分页
    使用jQuery实现option的上移和下移
    理解Flux架构
    React 入门学习笔记1
    ES6新特性6:模块Module
    ES6新特性5:类(Class)和继承(Extends)
    ES6新特性4:字符串的扩展
    ES6新特性3:函数的扩展
    ES6新特性2:变量的解构赋值
    ES6新特性1:let和const
  • 原文地址:https://www.cnblogs.com/lautung/p/13861880.html
Copyright © 2011-2022 走看看