zoukankan      html  css  js  c++  java
  • Python全双工聊天

    全双工聊天

    全双工聊天:服务端和客户端都可以发送并接收信息。

    使用select模块中的select方法

    select(rlist, wlist, xlist[, timeout]) -> (rlist, wlist, xlist)

    # server.py 服务器
    
    from socket import *
    from time import ctime
    import select 
    import sys
    
    HOST = ''
    PORT = 12346
    BUFSIZE = 1024
    ADDR = (HOST, PORT)
    
    tcpServer = socket(AF_INET, SOCK_STREAM)
    tcpServer.bind(ADDR)
    tcpServer.listen(5)
    gets = [tcpServer, sys.stdin]
    
    while True:
        print('Waiting for connection...')
        tcpClient, addr = tcpServer.accept()
        print('Connected from:', addr)
        gets.append(tcpClient)
    
        while True:
            readyInput, readyOutput, readyException = select.select(gets, [], [])
            for indata in readyInput:
                if indata == tcpClient:  
                    data = tcpClient.recv(BUFSIZE)
                    if not data:
                        break
                    print('[%s]: %s' % (ctime(), data.decode('utf-8')))
                else:
                    data = input()
                    if not data:
                        break
                    tcpClient.send(bytes(data, 'utf-8'))
        tcpClient.close()
    tcpServer.close()
    # client.py 客户端
    
    from socket import *
    from time import ctime
    import select 
    import sys
    
    HOST = 'localhost'
    PORT = 12346
    BUFSIZE = 1024
    ADDR = (HOST, PORT)
    
    tcpClient = socket(AF_INET, SOCK_STREAM)
    tcpClient.connect(ADDR)
    gets = [tcpClient, sys.stdin]
    
    while True:
        readyInput, readyOutput, readyException = select.select(gets, [], [])
        for indata in readyInput:
            if indata == tcpClient:
                data = tcpClient.recv(BUFSIZE)
                if not data:
                    break
                print('[%s]: %s' % (ctime(), data.decode('utf-8')))
            else:
                data = input()
                if not data:
                    break
                tcpClient.send(bytes(data, 'utf-8'))
    tcpClient.close()
    Resistance is Futile!
  • 相关阅读:
    POJ 3308 Paratroopers
    POJ 3228 Gold Transportation
    POJ 4786 Fibonacci Tree
    POJ 2987 Firing
    Models——英语学习小技巧之四
    Linux编程环境介绍(3) -- linux下的c/c++程序开发
    怎样使用Markdown
    windows系统中的dll的作用详细解释
    解决ListView 和ScroolView 共存 listItem.measure(0, 0) 空指针
    网页添加背景音乐
  • 原文地址:https://www.cnblogs.com/noonjuan/p/10815259.html
Copyright © 2011-2022 走看看