Python client socket event handling like that found in Adobe ActionScript

1.1k views Asked by At

I'm porting some ActionScript code to Python and I'm struggling with some sort of event dispatcher implementation similar to that available in Flash (flash.events.EventDispatcher).

I need to create a client socket connection to a server which will respond with a banner. The client will then send some information, receive a new banner etc.

I know how to create the client socket, but the problem is how to handle events, so that the client runs the appropriate functions depending on the events.

I've read a little about various modules such as Asyncore and Twisted and honestly I'm looking for something that is quick and easy to implement. I need to get the code ported with minimal fuss as a proof of concept.

Here is part of my code using asyncore:

import socket
import asyncore

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))

    def handle_connect(self):
        self.log('Socket connected')

    def handle_close(self):
        print "Socket disconnected"
        self.close()

    def handle_read(self):
        print 'Received: ', self.recv(1024)
        self.handle_close()

def connect(host, port)
    clientSocket = Client(host, port)
    asyncore.loop()

For some reason the code returns the following error:

warning: unhandled write event
warning: unhandled write event
warning: unhandled write event
...

The above code doesn't really do anything useful yet. I need to add event handlers for IO errors and for dealing with the data sent back and forth. However, first I need to get the basics sorted out.

Any help is greatly appreciated. Thanks.

1

There are 1 answers

1
Velociraptors On

Did you try overriding the handle_write event, as described in the asyncore documentation?

Edit: Alternatively, you can use the -W command-line option or the warnings module if you want to suppress the warning rather than override the event.