• 使用socket搭建一个网络聊天室


    #服务器端
    import socket import threading #创建一个TCP端 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #接受来自本地,4444端口的数据 sock.bind(('localhost', 4444)) #最大接受参数 sock.listen(5) print('Server', socket.gethostbyname('localhost'), 'listening ...') #创建一个空字典和一个空列表 mydict = dict() mylist = list() # 把whatToSay传给除了exceptNum的所有人 def tellOthers(exceptNum, whatToSay): for c in mylist:#遍历空字典 if c.fileno() != exceptNum: try: c.send(whatToSay.encode())#向tcp发送数据并编码为当前 except: pass def subThreadIn(myconnection, connNumber): nickname = myconnection.recv(1024).decode()#读取网络数据并解码 mydict[myconnection.fileno()] = nickname mylist.append(myconnection)#传入列表 print('connection', connNumber, ' has nickname :', nickname) tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 进入聊天室】') while True: try: recvedMsg = myconnection.recv(1024).decode() if recvedMsg: print(mydict[connNumber], ':', recvedMsg) tellOthers(connNumber, mydict[connNumber] + ' :' + recvedMsg) except (OSError, ConnectionResetError): try: mylist.remove(myconnection) except: pass print(mydict[connNumber], 'exit, ', len(mylist), ' person left') tellOthers(connNumber, '【系统提示:' + mydict[connNumber] + ' 离开聊天室】') myconnection.close() return while True: connection, addr = sock.accept() print('Accept a new connection', connection.getsockname(), connection.fileno()) try: # connection.settimeout(5) buf = connection.recv(1024).decode() if buf == '1': connection.send(b'welcome to server!') # 为当前连接开辟一个新的线程 mythread = threading.Thread(target=subThreadIn, args=(connection, connection.fileno())) mythread.setDaemon(True) mythread.start() else: connection.send(b'please go out!') connection.close() except: pass

      

    #客户端
    import socket
    import time
    import threading
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    sock.connect(('localhost', 4444))
    sock.send(b'1')
    print(sock.recv(1024).decode())
    nickName = input('input your nickname: ')
    sock.send(nickName.encode())
    
    
    def sendThreadFunc():
        while True:
            try:
                myword = input()
                sock.send(myword.encode())
                # print(sock.recv(1024).decode())
            except ConnectionAbortedError:
                print('Server closed this connection!')
            except ConnectionResetError:
                print('Server is closed!')
    
    
    def recvThreadFunc():
        while True:
            try:
                otherword = sock.recv(1024)
                if otherword:
                    print(otherword.decode())
                else:
                    pass
            except ConnectionAbortedError:
                print('Server closed this connection!')
    
            except ConnectionResetError:
                print('Server is closed!')
    
    
    th1 = threading.Thread(target=sendThreadFunc)
    th2 = threading.Thread(target=recvThreadFunc)
    threads = [th1, th2]
    
    for t in threads:
        t.setDaemon(True)
        t.start()
    t.join()
    

      

  • 相关阅读:
    Thrift实现C#调用Java开发步骤详解
    微信小程序项目实战之豆瓣天气
    带有关闭按钮的alertView
    基于olami开放语义平台的微信小程序遥知之源码实现
    iOS-仿智联字符图片验证码
    微信 支付宝支付 友盟登录分享 统计
    优化VMware提高虚拟机运行速度的技巧
    区块链与密码学
    在 Ubuntu 16.04 中安装支持 CPU 和 GPU 的 Google TensorFlow 神经网络软件
    Ubuntu+anaconda环境里安装opencv
  • 原文地址:https://www.cnblogs.com/haq5201314/p/8146569.html
Copyright © 2020-2023  润新知