For fun, I'm writing a minimal IRC server with asynchat. I'm trying to clear up a few fundamentals (my specific questions follow the code). I've decided not to use anything in Twisted just so I can implement a little more myself. First, the code I have:
import asyncore,asynchat
import socket
class Connection(asynchat.async_chat):
def __init__(self, server, sock, addr):
asynchat.async_chat.__init__(self, sock)
self.set_terminator('\n')
self.data = ""
print "client connecting:",addr
# do some IRC protocol initialization stuff here
def colle开发者_JAVA技巧ct_incoming_data(self, data):
self.data = self.data + data
def found_terminator(self):
print self.data
self.data = ''
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(5)
def handle_accept(self):
conn, addr = self.accept()
Connection(self, conn, addr)
def handle_close(self):
self.close()
s = Server('127.0.0.1',5006)
asyncore.loop()
So, in my mind, this code structure is similar to a Twisted client factory: the Server
class is initialized once and basically instantiates Connection
every time a client connects. First question: is the best way to keep track of all connected clients by storing all of the Connections in a list within Server
?
Also, I don't understand how I am to know when a specific client closes their connection to my socket? Connection
implements asynchat (and by extension asyncore) but adding the handle_close() callback to the Connection
class doesn't fire when a client disconnects. It seems to be only for when the bound socket on the server is destroyed. I don't see any methods for this purpose. This socket always stays open, whether or not clients connect, right?
to handle client side closed connections check the handle_error method, does your client issue a clean close connection? handle_error() :Called when an exception is raised and not otherwise handled. The default version prints a condensed traceback.
hope it helps.
精彩评论