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!
原文地址:https://www.cnblogs.com/noonjuan/p/10815259.html