Building a socket server with Node.js and Flash CS4

Node.js is very easy to use and very well designed. Today I’m going to build a simple socket server using the sample provided by the Node.js documentation and create a socket client in Flash CS4.

Updated July 30, 2010 – I’ve changed the Node.js Server code below to reflect the latest changes in the Node.js API changes as of version: 0.1.102. I also tested this in Flash CS5 and it worked.

I used the following to build this project:
1. Ubuntu 9.10 hosted in VirtualBox on Windows Vista
2. Flash CS4
3. Node.js

I also turned off the firewall in Ubuntu (not recommended but since I’m hosting it in VirtualBox and is already behind the router firewall I didn’t want to deal with any additional firewall issues – obviously in a production environment you need to think this through before disabling it)

I disabled the firewall in Ubuntu using this command:

ufw disable

Do so at your on risk!

Lets create the Flash CS4 project first. Create a new “Flash File (ActionScript 3.0)” and save it as “SocketExample”. My user interface look like this:

I named the interface components as such:
textarea – output_txt
textinput – input_txt
button (send) – send_btn
button (disconnect) – disconnect_btn

On the first frame of the timeline I added this ActionScript code:

var xmlSocket:XMLSocket = new XMLSocket();
// Adjust this to the IP address of your Linux machine/vm
xmlSocket.connect("192.168.1.100", 7000);

xmlSocket.addEventListener(DataEvent.DATA, onIncomingData);
send_btn.addEventListener(MouseEvent.CLICK, clickHandler);
disconnect_btn.addEventListener(MouseEvent.CLICK, disconnectHandler);

function clickHandler(event:MouseEvent):void
{
    xmlSocket.send(input_txt.text);
    input_txt.text = "";
}

function disconnectHandler(event:MouseEvent):void
{
    xmlSocket.close();
    send_btn.enabled = false;
}

function onIncomingData(event:DataEvent):void
{
    trace("[" + event.type + "] " + event.data);
    output_txt.text += event.data + "\n";
    output_txt.verticalScrollPosition = output_txt.maxVerticalScrollPosition;
}

If you haven’t worked through my Node.js tutorial do that first because I’m going to assume you have Node.js up and running.

Here is the Node.js code (taken mostly from the Node.js documentation):

var net = require("net"), sys = require('sys');
 
var server = net.createServer(function (stream) {
  stream.setEncoding("utf8");
  stream.on("connect", function () {
    stream.write("hello\0");
    sys.puts(sys.inspect(stream, false));
  });
  stream.on("data", function (data) {
    stream.write(data + "\0"); 
  });
  stream.on("end", function () {
    stream.end();
  });
});
server.listen(7000, "192.168.1.100");

Make sure to adjust the IP address as needed. Save the file as “tcp_server.js”.

Go ahead and run the script:

node tcp_server.js

Run the Flash SWF now and try it out.

Leave a Reply