首页 > 编程语言 > 详细

Python全双工聊天

时间:2019-05-05 19:03:49      阅读:159      评论:0      收藏:0      [点我收藏+]

全双工聊天

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

使用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()

 

Python全双工聊天

原文:https://www.cnblogs.com/noonjuan/p/10815259.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!