Tutorial: Building a Flash socket server with Java in five minutes

Post to Twitter

For many people who have used Adobe’s Flash or Flex products long enough they have probably at some point wanted to write a chat program, realtime applications (stock quotes, sports scores, etc.) or perhaps a multi-player online game but maybe the complexity kept you from actually doing that. Never fear, there are many great tools out there now to help you achieve this goal. Today we’ll look at xSocket and we’ll build a Flash CS3 application that connects to a socket server, posts some information that will be echoed back, and then we’ll “remotely” shutdown the socket server from our Flash application.

To complete this tutorial you will need the following:
1. A copy of Flash CS3/CS4 (the trial version will work if you don’t own it).
2. xSocket 2.2 (core)
3. The Java JDK 1.6
4. Netbeans 6.1

If you want to substitute Eclipse or whatever for Netbeans feel free to do so. Also, if you would rather do this using Flex Builder feel free to do that as well – just remember the tutorial will be based on the above software but it will work just fine using Flex and Eclipse, etc. with the appropriate changes.

Install and configure all the listed software first.

Next, download the xSocket 2.2 (core) jar file and save it somewhere like “C:\jars” or wherever you want. Start Netbeans and create a new Java application. From the Netbeans menu choose: File -> New Project and then choose: Java -> Java Application. Press the “Next” button and enter “xSocketServer” for the project’s name. Press the “Finish” button. Now, right-click on the “Libraries” and select the “Add Jar/Folder” and navigate to the place where you saved the xSocket.jar file and click on it.

Right-click now on the “xsocketserver” package under the “Source Packages” and add a new class. Call the new class “xSocketDataHandler.java”.

Go into the Main.java file and modify it to look like this:


package xsocketserver;

import org.xsocket.connection.*;

public class Main
{
    protected static IServer srv = null;

    public static void main(String[] args)
    {
        try
        {
            srv = new Server(8090, new xSocketDataHandler());
            srv.run();
        }
        catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }

    protected static void shutdownServer()
    {
        try
        {
            srv.close();
        }
        catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }
    }
}

All we are doing here is firing up xSocket and telling it to listen on port 8090 on our local machine. We also added a method that can be called to shutdown the xSocket server. We’ll get to that in a moment.

Move into the “xSocketDataHandler.java” file now and modify it to look like this:

package xsocketserver;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.channels.ClosedChannelException;
import org.xsocket.*;
import org.xsocket.connection.*;


public class xSocketDataHandler implements IDataHandler
{

    public boolean onData(INonBlockingConnection nbc) throws IOException, BufferUnderflowException, ClosedChannelException, MaxReadSizeExceededException
    {
        try
        {
            String data = nbc.readStringByDelimiter("\0");
            nbc.write(data + "\0");

            if(data.equalsIgnoreCase("SHUTDOWN"))
                Main.shutdownServer();
        }
        catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }

        return true;
    }
}

If you’ve read the xSocket tutorial this will look similar. We implement the IDataHandler interface which brings in the onData method where the real fun is. Keep in mind you should also implement IConnectHandler and IIdleTimeoutHandler but for the sake of keeping this tutorial done in five minutes we won’t do that.

We read the data that is handed to us from xSocket and simply return the same data back to the (Flash) client. We also listen to see if “SHUTDOWN” is passed and if so we close down the server. Obviously if you were to build a production socket server you would want to ensure not just anyone could call a remote shutdown on your socket server.

Keep in mind Flash and Flex expect “\0″ as their delimiter (always at the end of your transmissions).

Open up Flash and create a new ActionScript 3 project. We won’t be adding any UI to this at all so simply click on the first frame of the timeline and enter the following ActionScript:

var xmlSocket:XMLSocket = new XMLSocket();
xmlSocket.connect("127.0.0.1", 8090);

xmlSocket.addEventListener(DataEvent.DATA, onIncomingData);

function onIncomingData(event:DataEvent):void
{
    trace("[" + event.type + "] " + event.data);
}

xmlSocket.send("Hello World");
xmlSocket.send("SHUTDOWN");

- Keep in mind that its more proper to put your ActionScript code into *.as files (classes) rather than in the timeline, but again for simplicity and speed of our development we just add it to the main timeline.

XMLSocket in Flash is very easy to work with and we’ve done just enough to connect to the xSocket server and send two messages. Two messages will be echoed back, the last message tells the server to shutdown. Start your project in Netbeans first and let it run. Now, if you run the Flash project you should see the following trace output:

[data] Hello World
[data] SHUTDOWN

That’s it. As you can see using xSocket it is very powerful, yet very easy to build socket servers for your Flash and Flex projects. xSocket is not limited though to Flash and Flex, it can be used for much more so this is just the tip of the iceberg of the potential for this project.

Download the project files here.

Post to Twitter

This entry was posted in ActionScript, Adobe, Flash, Flex, Socket Server. Bookmark the permalink.

60 Responses to Tutorial: Building a Flash socket server with Java in five minutes

  1. Chad Lung says:

    @James,

    There are code samples for Java clients in the documentation: http://xsocket.sourceforge.net/core/tutorial/V2/TutorialCore.htm

    Chad

  2. James says:

    Oh, that what I thought after search for days. However, more tutorials would be appreciate since not many of us are Java experience but would like the powered of xSocket to intergrated into .Net and Flash.

  3. kevin says:

    can you help us with our game? it’s real time networking..

  4. Brian says:

    DOES not work. Please advise. I have tested this in my Linux, and i get error like this:

    Without java:
    [root@example ~]# nc -l 1020

    [root@example ~]# nc -l 8090

    With java (less then 1024 gives run fail):
    Permission denied
    BUILD SUCCESSFUL (total time: 0 seconds)

    With java (greater then 1024 port gives, using your example):
    run:
    Feb 3, 2011 3:32:51 PM org.xsocket.connection.Server$LifeCycleHandler onConnected
    INFO: server listening on 0:0:0:0:0:0:0:0:8090 (xSocket 2.8.15)

    channel is closed (read buffer size=0)

    channel is closed (read buffer size=0)

  5. dEEP says:

    cAN yOU pLEASE HELP for making Chat Server Using Swing And Socket Programming ….
    My Question is How to accept(Multiple Clients) Requets Using Only One Server
    ????????? Give Me the Code For that problem and How to Connect Database IN Java and Other Java Frames…..????????????Please Reply Me on MY E-Mail ID Please………………….

  6. janani says:

    me 2 getting the same result what Bryan get while i run in java..
    23 Mar, 2011 10:07:42 AM org.xsocket.connection.Server$LifeCycleHandler onConnected
    INFO: server listening on 0.0.0.0:8090 (xSocket 2.8.15)
    channel is closed (read buffer size=0)

    channel is closed (read buffer size=0)

  7. Dan says:

    @janani and @Bryan Whats your problem? thats the output you should expect! Does your Flash file show the correct trace? i.e.
    [data]Hello World
    [data]SHUTDOWN

    If so, then it has worked.
    Change your Main.java from this:
    srv = new Server(8090, new xSocketDataHandler());
    to:
    srv = new Server(“127.0.0.1″, 8090, new xSocketDataHandler());

    To stop it listening on 0.0.0.0

  8. Edward Montgomery says:

    Excellent. I need a simple way that I control to send data back and forth between Flex and Java. This is the first method I’ve found that is as easy as it should be. Great, simple example! Thanks!

  9. Clyde says:

    How would I make the Java server send things to a client(for example “Hello”), and then AS3 is coded to know if the Java server sent “Hello” so it can react?

  10. Jitechno says:

    Chad, is your example working for MacroMedFlash MX? ver 6.0 Trial?
    Did you check?
    Because I just assembled all step by step, put action script into 1st frame, alsoa s Button action( I wanrt fire message after click on button) , but I dont see connection to servrer.
    Also there is a problem to put
    xmlSocket.addEventListener(DataEvent.DATA, onIncomingData);
    function onIncomingData(event:DataEvent):void
    {
    trace(“[" + event.type + "] ” + event.data);
    }
    so I am trying only for this sending part
    var xmlSocket:XMLSocket = new XMLSocket();
    xmlSocket.connect(“127.0.0.1″, 8090);
    xmlSocket.send(“Hello World”);
    xmlSocket.send(“SHUTDOWN”);

    Thanks
    Ol

Comments are closed.