开发者社区> 问答> 正文

select()方法的循环

这是一个消息应用程序,可以发送消息从一个客户端到另一个客户端通过服务器,我调试这段代码,它是循环的read_socket, _, _ = select.select(self。输入,[],[],1) 用于读取read_socket: for ever。

import socket
import select
import errno
import sys

class client_app():

    def __init__(self):

        self.HEADER_LENGTH = 10
        self.IP = "127.0.0.1"
        self.PORT = 1234
        self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client_socket.connect((self.IP, self.PORT))
        self.client_socket.setblocking(False)
        self.inputs = [sys.stdin, self.client_socket]

    def client(self, send_message):
        while True:
            read_socket, _ , _ = select.select(self.inputs, [], [], 1)
            for read in read_socket:
                if read is client_socket:
                    try:
                        while True:
                            message_header = client_socket.recv(HEADER_LENGTH)
                            message_length = int(message_header.decode('utf-8').strip())
                            message = client_socket.recv(message_length).decode('utf-8')
                            print(message)
                    except IOError as e:
                        if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
                            sys.exit()
                        continue
                    except Exception as e:
                        sys.exit()
                else:
                    try:
                        message = send_message
                        if message:
                            message = message.encode('utf-8')
                            message_length = int(message_header.decode('utf-8').strip())
                            client_socket.send(message_header + message)
                    except IOError as e:
                        if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
                            sys.exit()
                        continue
                    except Exception as e:
                        sys.exit()

if __name__=='__main__':
    cli = client_app()
    cli.client('ahmad')
    cli.client('jan')```

问题来源StackOverflow 地址:/questions/59379805/looping-on-select-select-method-for-infinite

展开
收起
kun坤 2019-12-29 21:40:32 408 0
0 条回答
写回答
取消 提交回答
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载