Robert Bak – Notes

Some programming tips – updated sometimes

Basic socket server in AIR

The socket api is relatively simple, but I couldn’t find a simple step by step tutorial on getting sockets working. The basic idea was to create an app that can send text to connected clients (which I’ll be using to send code while teaching a Flex class), and getting that basic functionality working is amazingly simple with AIR 2+.

The config

To make life easier, first I’ve created a class that will hold the configuration for the socket, it’s nothing interesting, but as it will be used later, I’ll put it at the top. There are a few things to keep in mind while choosing the port – it needs to be smaller than 65536 and should be bigger than 1024 (see docs) and ports can’t be shared, so you need to make sure that the port you’re choosing isn’t already used 1.

public class SocketConfig
{
   static public const port:int = 9231;
   static public const address:String = "127.0.0.1";
}

The server – setup

Creating the server is really easy. We just need to set up an instance of the ServerSocket class, and start listening and handling incoming connections.

// create a server socket
protected var socket:ServerSocket = new ServerSocket();

protected function createServer(event:FlexEvent):void
{
   // bind the socket to a given address and port
   socket.bind(SocketConfig.port,SocketConfig.address);
   // the CONNECT event is dispatched after a client connects
   // to the socket, make sure we handle it
   socket.addEventListener(ServerSocketConnectEvent.CONNECT,
                           clientConnectedHandler);
   // start listening for connections
   socket.listen();
}


As it’s supposed to push data to multiple clients, here’s the code to keep track of the connections,

[Bindable] // for keeping track of the clients
protected var clientSockets:ArrayCollection = new ArrayCollection();

// adds the client to the list and adds the disconnect handler         
function clientConnectedHandler(event:ServerSocketConnectEvent):void{
   clientSockets.addItem(event.socket);
   event.socket.addEventListener
      (Event.CLOSE,clientDisconnectedHandler);
}
           
function clientDisconnectedHandler(event:Event):void{
   clientSockets.removeItemAt(
         clientSockets.getItemIndex(event.target));
   event.target.removeEventListener
         (Event.CLOSE,clientDisconnectedHandler);
}

The client – setup

Setting up a client is as easy, if not easier. You just need to create a Socket, add event listeners to link some logic to it and connect to the server (using it’s address and port)

// create our client socket
protected var socket:Socket = new Socket();

protected function createSocket(event:Event):void
{              
   // get notified when the socket connects
   socket.addEventListener(Event.CONNECT,socketConnected);
   // get notified when there's data
   socket.addEventListener(ProgressEvent.SOCKET_DATA,socketData);
   // connect
   socket.connect(SocketConfig.address,SocketConfig.port);
}

We can create functions with trace statements to check if the connection works and, as the only thing this server will be sending will be strings, output the data is being sent.

protected function socketConnected(e:Event):void{
   trace("client - socket connected");
}
           
protected function socketData(e:ProgressEvent):void{
   trace("client - socket data");
   // read the string from the socket
   trace(socket.readUTF());
}

The server – finishing

The last thing we need to do is send the data to sockets, we’re going to use the writeUTF 2 of the socket. Notice that this function is called on each of the connected sockets (stored in the clientSockets collection) and not on our ServerSocket instance. It’s also important to flush the data to the socket once finished to make sure the data is sent.

protected function writeDataToSockets(event:Event):void
{
   for each (var sock:Socket in clientSockets){
      sock.writeUTF("test");
      sock.flush();
   }
}

That’s it, now we have a fully working server which can push data to clients over TCP.

Please remember that this is a very basic example with no code for error handling, etc. Just enough code to get it working. The very last thing to do is make sure we release the port once the server application closes.

protected function applicationCloseHandler(event:Event):void
{          
    socket.close();
}

The source code has some additional code for the UI.
Download source code.

Notes:

  1. Remember to close the socket when closing the app, otherwise you might run into trouble when launching it again
  2. writeUTF has a limit on string length – it needs to be shorter than 65536

4 thoughts on “Basic socket server in AIR

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>