这是一个消息应用程序,可以发送消息从一个客户端到另一个客户端通过服务器,我调试这段代码,它是循环的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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。