我有一个IP =“127.0.0.1”,端口号“port”,并且正在尝试
class AClass(asyncore.dispatcher):
def __init__(self, ip, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((ip, port))
def handle_connect(self):
print 'connected'
def handle_read(self):
data = self.recv(8192)
print data
def handle_close(self):
self.close()
但没有打印任何内容。
发送正在由另一个进程处理。我该如何检查?以上正确吗?
编辑: 用于发送:一个不同的Python程序,单独运行:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((addr, port))
packet="some string"
sock.sendall(packet+'\r\n')
什么也没发生
如果我放在服务器端(!!!)
print sock.recv(4096)
我看到打印的数据包 - 但客户端仍然没有任何反应。
我假设你的意思是
AClass
是服务器端。在这种情况下,AClass
不应该 做 connect()
。套接字通信有两个方面。在服务器端,您通常创建套接字,将其绑定到地址和端口,设置积压(通过
listen()
)和
accept()
连接。通常,当您从客户端获得新连接时,您会生成其他一些实体来处理该客户端。此代码实现了一个回显服务器:
import asyncore
import socket
class EchoHandler(asyncore.dispatcher_with_send):
def handle_read(self):
self.out_buffer = self.recv(1024)
if not self.out_buffer:
self.close()
print "server:", repr(self.out_buffer)
def handle_close(self):
self.close()
class EchoServer(asyncore.dispatcher):
def __init__(self, ip, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((ip, port))
self.listen(1)
def handle_accept(self):
sock, addr = self.accept()
print "Connection from", addr
EchoHandler(sock)
s = EchoServer('127.0.0.1', 21345)
asyncore.loop()
请注意,在
__init__()
方法中,我正在绑定套接字并设置积压。
handle_accept()
是处理新传入连接的。在这种情况下,我们获取从
accept()
返回的新套接字对象和地址,并为该连接创建一个新的异步处理程序(我们将套接字提供给
EchoHandler
)。然后
EchoHandler
执行从套接字读取数据的工作,然后将数据放入
out_buffer
中。然后,
asyncore.dispatcher_with_send
会注意到数据已准备好发送,并将其写入幕后的套接字,后者将其发送回客户端。所以我们有双方,我们从客户端读取数据,然后转身并将相同的数据发送回服务器。您可以通过多种方式检查此实现。下面是一些用于打开连接、发送消息、读取响应并退出的 Python 代码:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((ip, port))
client.sendall("Hello world!\r\n")
print "client:", repr(client.recv(1024))
client.close()
在此示例中,您还可以使用命令
telnet localhost 21345
将 telnet 用作客户端。输入一个字符串,按回车键,服务器将发送回该字符串。这是我所做的一个示例会话:
:: telnet 127.0.0.1 21345
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello!
Hello!
aouaoeu aoeu aoeu
aouaoeu aoeu aoeu
^]
telnet> quit
Connection closed.
在示例中,第一个“Hello!”是我在客户端输入的,第二个是来自服务器的回显。然后我尝试了另一个字符串,它也得到了回显。
如果你以前没有做过套接字通信,我真的不能推荐Richard Stevens
UNIX网络编程。第三版现已印刷并可在Amazon上购买。但是,它不包括使用 Python 或 asyncore。不幸的是,asyncore 这个模块在 Python 文档中并没有得到很好的介绍。不过,市面上有一些相当不错的例子。
希望这能让您朝着正确的方向前进。
编辑:这是一个基于异步的客户端:
class Client(asyncore.dispatcher_with_send):
def __init__(self, ip, port, message):
asyncore.dispatcher_with_send.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((ip, port))
self.out_buffer = message
def handle_connect(self):
print 'connected'
def handle_read(self):
data = self.recv(8192)
print "client:", repr(data)
def handle_close(self):
self.close()