我正在学习Python中的套接字,并且一直在使用着名的echo服务器。我正在尝试将asyncore
库用于异步IO,但我从客户端套接字中得到了这种奇怪的行为。
这是我写的代码:
import socket
import asyncore
class Handler(asyncore.dispatcher):
'''
Class to handle connected clients and send them messages.
'''
def __init__(self, sock, server):
asyncore.dispatcher.__init__(self, sock)
self.server = server
self.buffer = 'Connection accepted'
def writable(self):
return len(self.buffer) > 0
def handle_read(self):
'''
Read from the buffer.
'''
data = self.recv(2)
if not data:
raise RuntimeError('Lost connection to client.')
print 'Handler received: %s' % data
def handle_write(self):
sent = self.send(self.buffer)
print 'sent %d bytes' % sent
self.buffer = self.buffer[sent:]
class Server(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind((host, port))
self.listen(1)
def handle_accept(self):
self.client, _ = self.accept()
self.handler = Handler(client, self)
if __name__ == '__main__':
port = 5655
server = Server('', port)
client = socket.socket()
client.connect(('localhost', port))
asyncore.loop(0.1, count=5)
client.send('hi')
print 'Client received: %s' % client.recv(19)
asyncore.loop(1, count=1)
当我尝试将客户端套接字连接到服务器时,它根本无法与处理程序进行通信。这是发生的事情:
Traceback (most recent call last):
File "test.py", line 57, in <module>
print 'Client received: %s' % server.client.recv(19)
socket.error: [Errno 10035] A non-blocking socket operation could not be completed immediately
但是,如果我使用服务器的accept
方法而不是原始客户端套接字返回的客户端套接字,它会按预期工作:
if __name__ == '__main__':
port = 5655
server = Server('', port)
client = socket.socket()
client.connect(('localhost', port))
asyncore.loop(0.1, count=5)
server.client.send('hi')
print 'Client received: %s' % server.client.recv(19)
asyncore.loop(1, count=1)
输出:
sent 19 bytes
Client received: Connection accepted
Handler received: hi
我做错了什么,还是预期的行为?如果后者是真的,我真的需要提高对套接字的理解。