有两个文件:server.py 和 client.py,都是在 asyncore.dispatcher 的帮助下编写的
服务器.py
import asyncore, socket
class Server(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind(('', port))
self.listen(1)
print "Waiting for connection..."
def handle_accept(self):
socket, address = self.accept()
print 'Connection by', address
socket.send("Hello Server")
def handle_read(self):
print "Reading..."
out_buffer = self.recv(1024)
if not out_buffer:
self.close()
print out_buffer
def handle_closed(self):
print "Server: Connection Closed"
self.close()
s = Server('0.0.0.0', 5007)
asyncore.loop()
客户端.py
import asyncore, socket
class Client(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((host, port))
print "Client Start..."
def handle_close(self):
print "Client: Connection Closed"
self.close()
def handle_read(self):
data = self.recv(1024)
if data:
print "Received ", data
self.send("Hello Client")
c = Client('127.0.0.1', 5007)
asyncore.loop()
结果:
执行server.py
:
Waiting for connection...
然后client.py
:
Client Start...
Received Hello Server
Client: Connection Closed
Client: Connection Closed
最后client.py退出了,server.py的输出窗口又显示了一行,服务器继续运行:
Connection by ('127.0.0.1', 58197)
有一点我无法理解:
为什么client.py
handle_closed
中的函数执行了两次?为什么server.py
handle_reading
中的函数没有执行?client.py发送了 message( " Hello Client"),但是为什么服务端收不到呢?为什么server.py
handle_closed
中的函数没有执行?当客户端退出时,我想在server.py中执行一些代码,但似乎它在server.py中没有任何作用?handle_closed