Python XML Socket: how to create a chat with Adobe Flex, AIR and Python

In last few weeks I start to integrate Python with Flash Platform using XML and now with XML Socket.

There are some methods to make a connection from a Python to Flash or Fle; you can use XML or PyAMF, that is a way to communicate between an application and a remote server with a compact binary representation that can be transferred over HTTP/HTTPS.
You can also work with XML Socket to create a fast and 2 ways communication between Python and Flash or Flex.
In this case we’ll use XML Socket to create a chat application where Python will be our server-side language and Flex and AIR will be our desktop application.
If you work for the first time with AIR you must know few things that help you to understand better the AIR world.

AIR (Adobe Integrated Runtime) is a new Adobe technology that allow developers and designers to bring online contents and, with the same programming language, work on desktop environment.

If you want to install an AIR application you MUST have AIR runtime installed in your computer, you can download it directly from Adobe site and it’s totally free and CROSS-PLATFORM!
In fact when you deploy an AIR application you can deliver it on MAC OS, WIN or Linux and you don’t change anything! This is amazing!

AIR integrates 4 web technologies together like HTML, Javascript, SWF and PDF and they could work together if you need it.
To work with Flex and AIR you only install in Eclipse or Aptana the Flex Builder plug-in that you can find on Adobe site, or if you don’t use those IDE, you can download Flex Builder standalone version that integrates both technologies.

So now we start to talk about our first experiments with Python, AIR and Flex.
First of all, you can create a Python file with this code:

# import socket and select module

import socket, select

# define checkData function that is the core of our Socket comunication

def checkData():

#create an infinitive loop to check data from an AIR client to another one

    while True:

# use select module to allow an application to wait for input from multiple sockets at a time

inputready,outputready,exceptready = select.select(input,[],[])

        for s in inputready: 

            if s == theSock: 

            # add a client to the socket connection

                client, address = theSock.accept() 

                input.append(client) 


            else:

            # comunication between client and server: manage traffic data

                data = s.recv(1024)

# in tempConn we put all client without server connection 

                tempConn = input[1:len(input)]

                if data:

                    for i in tempConn:

# send to all client any messages

                        i.send(str(i.getsockname()[0]) + “: ” + data)

                else:client.close()

#define socket connection: address, port and type of socket connection

theAddress = (’localhost’,1024)

theSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

theSock.bind(theAddress)

theSock.listen(5)


input = [theSock]

#after established XMLSocket connection, manage messages from client

checkData()

OK, Python side we have done!

Now we start with Flex/AIR part, so I comment all steps, if you have any suggestions or doubt feel free to add a comment and will be a pleasure to reply:

After create a new Flex project in Eclipse or Flex Builder, based on Adobe AIR you can find 2 files in src folder: an .mxml file and a .xml file.
The first one is a Flex file (mxml is Flex format file) where you can define your GUI and, with Actionscript 3, logic of your AIR application; the second one is an XML configuration file of your desktop application where you can sets a lots of parameters like size of your application, name of window, type of window and so on.
I suggest to take a look at Adobe Devnet site where you can find lots of tutorial about Flex, Flash, AJAX and AIR.

In our Flex project copy and paste this code:

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:WindowedApplication xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”init()”>

<mx:Script>

<![CDATA[

private var srv:XMLSocket;

private function init():void{

srv = new XMLSocket()

srv.addEventListener(DataEvent.DATA, traceData)

srv.addEventListener(IOErrorEvent.IO_ERROR, setErr)

srv.addEventListener(Event.CONNECT, getConn)

srv.addEventListener(Event.CLOSE, closeHandler);

srv.connect("localhost", 1024)

}

private function closeHandler(e:Event):void{

chatMessage.text += "//****LOGOUT FLAIRPY CHAT****\\";

}

private function getConn(e:Event):void{

chatMessage.text += "//****LOGIN FLAIRPY CHAT****\\";

}

private function setErr(e:IOErrorEvent):void{

chatMessage.text += e.text;

}

private function traceData(e:DataEvent):void{

chatMessage.text += e.data + "\n"

}

private function sendMessage():void{

srv.send(lblT.text);

}

]]>

</mx:Script>

<mx:VBox width=”50%” height=”50%>

<mx:HBox>

<mx:TextInput id=”lblT” width=”100/>

<mx:Button label=”send” click=”sendMessage()”/>

</mx:HBox>

<mx:TextArea id=”chatMessage” editable=”false” width=”100%” height=”50%/>

</mx:VBox>

</mx:WindowedApplication>

In the Script tag you can find all Actionscript language that allow you to connect your AIR application to Socket and how to manage all events that Socket triggers when you work with AIR application.
In fact we are listen events (srv.addEventListener(…)) when Socket connection start, close and when we receive data from other Socket connection, in Actionscript you work mainly with asynchronous methods, only with some AIR API (we take a look at that in next blog posts) you can work synchronous methods.
In MXML language we have define all GUI of our desktop application, in particular we use some containers to organize our GUI (HBox, VBox, and so on) and in those components we put a textarea, to show chat history, a textinput that allow user to send a message to the server, and a button that call a function (sendMessage()) where send messages to our XML Socket.

Finally to test this sample, remember to launch first Python script and then AIR application, if you don’t make this sequence AIR application thrown an error when you try to send a message to the server.

TIPS&TRICKS: if you try to send a string from Python to Flex/AIR application, remember to close your sentence with “\0″ because client side must understand when string terminate.

I upload also sources code to download Python and Flex/AIR samples.
For any questions please leave a comment at this post

Tags: , , , , , , , , ,

11 Responses to “Python XML Socket: how to create a chat with Adobe Flex, AIR and Python”

  1. freevryheid says:

    nice! code for python 2.6+ I’m guessing (attribute AF_INET missing in 2.5). Time to upgrade I guess :)

  2. great job!
    is this code running on google apps?

  3. admin says:

    Hi Piergiorgio,

    I don’t know if it runs on google apps, I don’t take a look but I’ll read more about it and I’ll reply you.
    Thank you to follow Flairpy.com

  4. dwi says:

    Regarding AF_INET being missing. Most likely the user is experiencing the script import itself during the import socket line. Renaming the script to somethingelse.py and making sure no socket.py exist in the current working directory will let the script work. I’m guessing the IDE used isn’t putting “.” as the first path of the import search path.

  5. Zen says:

    Cool!
    How would you go about ruing this on a server?

  6. It’s the first time I comment here and I must say that you share us genuine, and quality information for other bloggers! Great job.
    p.s. You have a very good template . Where have you got it from?

  7. Your blog is a rich source of information on dating and personals. Liked it, will bookmark it for later!

  8. Chris says:

    Awsome post. Lots to learn. Your code example works (finally got everything working)… it will continue to establish connections and sends to all, but as soon as 1 client leaves (for example you close 1 browser), the code crashes. I’ve been trying to track down the problem (learning python as I go, heh) but aside from that, this was a great start. I wont bug you for a fix, as this is a good opp to learn, but given all the headaches with sockets I may just go the FMS App rout and talk back and forth with netconnection and back/forth functions.

  9. Chris says:

    Looks like you’ve got some reply spam (hydrolic car & free dating?? heh) :)… enable one of the default wordpress anti-spam plugins if you havent already…usually solves prob… and if that does not work, plug “recaptia” in.

    Else the site is doing a great job advertising for those samp URLs :)

  10. Chris says:

    Ah… the code spirals in to an infinate loop if you close one of the clients. You can shove a print statment inside the while and see it spiral out of control after you close/disconnect 1 of the clients.

  11. Chris says:

    i got it working… not that you care, but your code did not handle any removal of clients (maybe you intended it that way because it was a quick example but… if not, thats why it crashed).. for anyone else reading this response :) you need to add to the code/modify it wiht a few more conditions and vars and keep better track of clients += 1 or clients -= 1/input.remove(s)/outputs.remove(s) etc.

    This is the only code I’ve seen anywhere on the way that’s actually brief and works out of the box with the exception of the crashing when you remove a client, but if look at some of the other examples, you can see that this code mimics some of the other examples floating around there that *do not work, and if you piece them & this code together… well I got it working… after 2 days & not knowing anything about Python.

    Thanks :)… powerfull stuff.

Leave a Reply