Networking | 131
// endpoint.
socket.writeUTFBytes( "Bob" );
// Send the actual bytes to the server and clear
// the stream. We then wait for data to be sent
// back to us.
socket.flush( );
}
The air.ProgressEvent.SOCKET_DATA event is dispatched
whenever data is received. The service we are connecting to
uses a simple protocol: we send a UTF-8 encoded string and
it returns a UTF-8 encoded string. This makes accessing the
data sent back to us very simple. To access this data, we
measure the total bytes of data available on the Socket and
read that many bytes as a UTF-8 encoded string using the
read readUTFBytes( ) method of the Socket class.
function onSocketData( event )
{
var data =
socket.readUTFBytes( socket.bytesAvailable );
air.trace( data ); // Hello Bob
}
In our example, the protocol of communication was just a
single string. In some cases, depending on the service with
which you’re communicating, you may need to send and
receive other data types. The Socket class provides methods
for reading and writing many data types, such as ints, Bool-
eans, floats, etc. For example, if we were talking with a fic-
tional service that required us to send a Boolean followed by
an int, ouronSocketOpenfunction in the above example could
look like this:
function onSocketOpen( event )
{
// First send the boolean
socket.writeBoolean( true );
// Now send an int
socket.writeInt( 10 );