130 | Chapter 4: AIR Mini-Cookbook
you send data to a persistent socket endpoint and receive data
from it in real time. You do not need to create a newSocket
instance for each set of data sent to the same endpoint. The
connection can be kept alive for the entire conversation
between your client and the service to which you’re connect-
ing. This is the typical flow when using the Socket API:
1.Create a connection to the endpoint
2.Listen for notification of connection success or failure
3.Queue data that will be sent to the endpoint
4.Send the data to the endpoint
5.Listen for data incoming from the endpoint
6.Repeat steps 3 through 5
7.Close the connection
The first step is to create a connection to the socket end-
point that consists of a host and a port number. For example,
to connect to an endpoint the host might be ‘foo.com’ and
the port number might be 5555. Create the instance of the
Socketclass and connect to the endpoint using that informa-
tion. At this time, we will also set up our listeners to listen
for the different events that the Socket can dispatch:
var socket = new air.Socket( );
socket.addEventListener( air.Event.CONNECT, onSocketOpen );
socket.addEventListener( air.ProgressEvent.SOCKET_DATA,
onSocketData );
socket.connect( 'foo.com', 5555 );
We will also need to create the functions to handle the events
we subscribed for. The first event is theair.Event.CONNECT
event. This event will tell us when the socket has been initi-
ated and communication with the service behind the end-
point is possible. In this example, we are sending the bytes of
a UTF-8 encoded string to the service:
function onSocketOpen( event )
{
// This queues up the binary representation of the
// string 'Bob' in UTF-8 format to be sent to the