By: Derek Santos
Socket driven applications have several benefits. The benefits include real-time data interchange between the Client and Server, and giving the developer more control over how the data is sent. This post will cover some basics about sending xml data over sockets, and how the socket performs with large data sets.
Setting Up a Socket Server
The first thing you need to do is create a socket server. This can be done with Java via the ServerSocket class. Please refer to the attachments to see how this is done. In this example, we will be connecting to a socket on port 5678. It’s important to note that since Flash Player 9.0.124.0, a policy file is required to be served by the socket. You can serve a policy file on port 843, which will allow any subsequent socket connections for any port on that host. A Policy File server is also provided in the attachments. In this example, the Java Socket Server simply responds to a request and returns “n” number of xml rows back to the client. The Socket Server will return the data in intervals, rather than all at once. The purpose of this example is to determine at what interval you can achieve the best performance.
Below is the xml we will be expecting from the server.
<person>
<id>1</id>
<name>Derek Santos</name>
<company>New Toronto Group</company>
</person>
Once our Socket Server is up, we can make requests to the server from the Client. To do this, you can use the XMLSocket class.
var socket:XMLSocket = new XMLSocket();
socket.connect(‘localhost’, 5678);
This will an attempt to connect to the socket server we have created. We also need to listen for the connect event of the socket, so that we can begin sending requests.
socket.addEventListener(Event.CONNECT, connectHandler);
private function connectHandler(event:Event):void {
socket.send(“my first socket request”);
}
Although it is an XMLSocket, you are not required to send data in XML format. In fact, the server does not know the difference between an xml socket and a regular socket connection. You can handle results from the server by adding an event listener on the socket for the DataEvent.
socket.addEventListener(DataEvent.DATA, dataHandler);
XMLSocket Test Results
The screenshot below shows a simple Flex application which asks the server for XML data. First it asks for 10,000 rows, then 100,000 and then 1,000,000 rows. The chart below represents the time it took to retrieve all of the rows(y axis), and how many rows at a time were returned(x axis).

This test was run on dual-core processor with 2GB of ram. Interestingly, it looks like the optimal setting is around 32 rows per result.
You can download all of the source for this example below.
Download Source Code