O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Receiving Data

Problem

You want to read data from a socket server.

Solution

For Socket instances, subscribe to the socketData event and invoke one of the read methods, such as readByte() or readInt(), in the event handler, making sure not to read past bytesAvailable.

For XMLSocket instances, subscribe to the data event and interpret the XML data received inside of the event handler.

Discussion

Receiving data from a socket connection depends on the type of socket you use. Both Socket and XMLSocket are capable of receiving data from a server, but they do so using slightly different techniques. Let’s focus on how the Socket class works first before discussing XMLSocket.

As you’ve learned in the introduction to this chapter, sockets in Flash behave asynchronously. Therefore, it’s not possible to simply create a socket connection and attempt to read data from the socket right away. The read methods don’t wait for data to be transferred from the server before returning. Instead, you can only read data from a socket after the client has already downloaded the data from the host server. It is an error to try and read data from a Socket before any data is available.

To know when data is available to be read, the socketData event is broadcasted from Socket instances. By adding an event listener for the socketData event, your event handler is invoked anytime there is new data received from the socket server. Inside the event handler is where you write code to read and interpret the received data. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required