• socket群聊服务端-客户端


    import socket
    import sys
    import _thread as t
    dictd={}
    listd=[]
    
    def boradcast(fileno,message):
        for conn in listd:
            if conn.fileno()!=fileno:
                conn.sendall(message.encode())
    
    
    def cilentThred(conn,fileno):
        conn.sendall("欢迎:{0}".format(fileno).encode())
        data = conn.recv(1024).decode()
        dictd[fileno] = data
        listd.append(conn)
        print("昵称为:{0}".format(dictd[fileno]))
        boradcast(fileno,"[系统提示:<{0}>进入聊天室]".format(dictd[fileno]))
        while True:
            try:
                datadd = conn.recv(1024).decode()
                if datadd:
                    print("【消息】{0}:{1}".format(dictd[fileno], datadd))
                    boradcast(fileno, "{0}:{1}".format(dictd[fileno],datadd))
            except :
                try:
                    listd.remove(conn)
                except:
                    pass
                print("[日志]{0}退出聊天室,当前聊天室人数为{1}人".format(dictd[fileno],len(listd)))
                boradcast(fileno, "【系统提示】:{0}离开聊天室".format(dictd[fileno]))
                conn.close()
                return
                pass
    try:
        sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        print('服务器socket创建成功')
    except:
        print('创建失败')
        sys.exit(0)
    address=('172.3.14.125',8898)
    sockets.bind(address)
    sockets.listen(5)
    while True:
        conn, addr = sockets.accept()
        print('客户端{0}连接成功'.format(conn.fileno()))
        t.start_new_thread(cilentThred,(conn,conn.fileno()))
    conn.close()
    import socket
    
    import threading
    
    import sys
    
    try:
        sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        print('客户端socket创建成功')
    except:
        print('创建失败')
        sys.exit(0)
    
    address=('172.3.14.125',8898)
    
    sockets.connect(address)
    data = sockets.recv(1024).decode()
    print(data)
    nic=input("输入昵称:")
    sockets.sendall(nic.encode())
    
    def send():
        while True:
            try:
                myword=input("请输入:")
                sockets.sendall(myword.encode())
            except:
                pass
    def reced():
        while True:
            try:
                otherword=sockets.recv(1024).decode()
                if otherword:
                    print(otherword)
            except:
                pass
    
    t1=threading.Thread(target=send)
    t2=threading.Thread(target=reced)
    t2.start()
    t1.start()
    
    #t1.join()
    
    #sockets.close()

     

  • 相关阅读:
    spock2.x结合mockito静态mock
    线程池的拒绝策略及常见线程池
    正确关闭线程池
    对线面试官 | 字节跳动一面
    记一次oom问题排查
    MySQL索引下推,原来这么简单!
    vs2019 编译 protocol buffers
    每日一库:classList.js
    每日一库:tinycon.js
    算法: 有效的括号
  • 原文地址:https://www.cnblogs.com/huazhou695/p/9990207.html
Copyright © 2020-2023  润新知