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. Pingback: ??xSocket 5????Java????Flash socket server??? | ??Flex??

  2. cease says:

    how does xsocket differ from blazeds or live data services

  3. Chad Lung says:

    @cease,

    BlazeDS and LCDS would be used for things like RMTP, AMF, etc. whereas a socket server perhaps built with Apache Mina or xSocket can have a TCP socket connection that stays connected the entire time and thus able to do realtime updates.

    Generally speaking socket servers can have issues with firewalls, typically BlazeDS and LCDS can get around those issues easier.

    xSocket and BlazeDS serve different application needs. Example: I might use a socket server for games and chat applications. I might use BlazeDS to do a stock quote application that provides near realtime stock data.

    Chad

  4. Pingback: Giant Flying Saucer » Blog Archive » Building a Multi-user Chat Server with xSocket, Java, and Flash CS3

  5. sly says:

    great tutorial and it helped me a lot but I have a question regarding xSocket. What should I do If I want that my java program simultaneously communicate with another program/device? Should I:
    a)start new server ( srv2 etc.),
    b)use existing server and start only no socket connection,
    c)I can use existing socket connection

    I tried the first option And I wrote that code. I donät get any error but It doesn’t work. What am I doing wrong?

    try
    {
    srv2 = new Server(8091, new xSocketDataHandler());
    srv2.run();
    }
    catch(Exception ex)
    {
    System.out.println(ex.getMessage());
    }
    }

  6. sly says:

    I meant “communicate with another program/device which has its own IP”

  7. Chad Lung says:

    @sly,

    Sounds like more of a question for the xSocket mailing list:

    https://lists.sourceforge.net/lists/listinfo/xsocket-develop

    Chad

  8. Flash Free says:

    This is a great blog!

  9. Bryce says:

    How Do I change the ip address? Right now its coming out as 0.0.0.0

  10. Pingback: » flex app communicate with java via socke … Doing & Done

  11. wobalisk says:

    how can I avoid security problems? It works fine in flash but when I try to load the file through other methods it does not work. can anyone help?

  12. Pingback: Security Error #2048

  13. Ciccio says:

    Hello! I have Bryce’s same problem…

    first time it was listening on 127.0.0.1, now it’s listening on 0.0.0.0 and obviously it doesn’t work anymore.
    What can it be? Any idea?!?

  14. Chad Lung says:

    @Ciccio,

    You might want to get on xSocket’s mailing list and ask that question.

    Chad

  15. El Zorro says:

    Very nice tutorial!
    great, keep on!

  16. Lorenz says:

    “INFO: server listening on 0.0.0.0:8090 (xSocket 2.5)”

    Why does it listen on 0.0.0.0 ??? O.o ???

  17. Lorenz says:

    ok i found the problem.
    in the main.java you need to replace:

    srv = new Server(8090, new xSocketDataHandler());

    to

    srv = new Server(“127.0.0.1″, 8090, new xSocketDataHandler());

  18. Julian says:

    Yello.

    This post is great! http://giantflyingsaucer.com/blog/?p=205… I must remember that so i can make something soon!

  19. Cam says:

    How do you read from the socket? This example shows how to send data to it, but how could you receive data from it (via flash)?

  20. Chad Lung says:

    @Cam,

    I don’t understand your question. Both Flash and XSocket (Java) are sending and receiving data in the example above.

  21. Cam says:

    I meant from a different flash app.
    Say you have flash1 sending and flash2 waiting for a reply. I ended up saving the sent value from flash1 as a var in the java app and then requesting that variable in flash2. I was looking for a way to do this:

    flash1—->socketserver—->flash2

    my current set up is:

    flash1—-> socketserver—> var
    flash2<—- var

  22. Zeger says:

    Hi

    I have a problem…
    Why when i test movie in flash it work, but when i execute my swf file it’s doesn’t work?

  23. CodeJustin says:

    Wow, this is seriously just what I was looking for (to get the concept of how to implement a java socket server into flash)!

    Thanks a lot you really helped clear up a few questions I had… now I’m onto to tackle making a decent socket server =)

  24. ozi says:

    hi
    i got a question also, let say we have multiple clients connecting to the server, does the server socket keep a list of all the address of the clients if saw how can i access it???

  25. Thanks!!! Nice post!

  26. law says:

    thousand thanks of sharing your though………

  27. Adam says:

    Hi,
    Could I also have this setup on my remote server? Works great on my local, but I’d like to use it for Flash app on my website too.

  28. bcnobel says:

    It’s probably just me, because this is a stupid problem which i’ve never had before,
    but why doesn’t my .swf file do anything while my test movie works perfectly?

  29. bcnobel says:

    Sry for double posting, but nvm about my question…
    my .swf still isn’t working, but i tried creating a projector, and that did work!

    Strange…

  30. Mateusz says:

    @bcnobel

    I think it’s because of some security sandbox issues. Try adding listeners for security end io erros on xmlSocket object and print/alert them in your app. Hope this helps!

  31. validator says:

    I want to make a multi player game. is xsocket enough for multi player game. Thanks.

  32. Chad Lung says:

    @validator,

    That depends on a lot of things. Is it a “twitch” game? How many players are you wanting to support? What is the hardware your using, etc.

    Chad

  33. PlepNL says:

    Oh man, u changed this tut from as2 to as3.
    thats great, because i’ve been trying to convert my earlier projects from as2 to as3, including this one.

    One problem though, in the as2 version of this tut, java used a ‘public static void’ to send the messages back to the clients, unlike the ‘public boolean’ java uses in this one.
    My problem is that i want java to check the type of request first (like login, register, or message-send), and after it’s done that, i want it to call the ‘public static void’ to return the message if needed.

    is there any way some1 could send me an example of this void by email, so i can try and implement it in my own source?

    thx in advance…

  34. PlepNL says:

    Oh, never mind my last post, i found it after a reeeeel long search on google…

    If anyone else is interested in the as2 source and a more advanced server source, get it here:
    http://giantflyingsaucer.com/blog/?p=224

  35. christian louboutin says:

    it is interesting and informative article. This has been very helpful understanding a lot

    of things. I’m sure a lot of other people will agree with me.

  36. Manish Sohaney says:

    How do I call Main method? I mean how does the port 8090 get open?

  37. Dimitry says:

    From Russia with appreciation!) Thank you for article)

  38. TEB says:

    Hello,
    This was just what I’ve been looking for – thanks. However I’m having some trouble… I’m new to Java and I’m trying to export it from Eclipse.

    It works fine in the Eclipse IDE but when I export it as a JAR I can’t figure out how to run it. I’m getting this error:
    Exception in thread “main” java.lang.NoClassDefFoundError: xsocketserver/Main

    I’ve tried to include class paths, I was told that I could access a JAR inside a JAR, I’ve tried extracting the files from the JAR and doing it that way but no.

    Can you please advise on how I can export this for general use.
    Thanks

  39. Sebb says:

    Thx! very helpfull :)

  40. Pingback: Building a Flash Chat Socket Server with Stackless Python « Giant Flying Saucer

  41. Pingback: Getting Perl and Flex talking via XML « Giant Flying Saucer

  42. Florian says:

    It works quite well on my pc. Thank you!

    How can I actually put this on a server so two clients can communicate via internet?

  43. Chad Lung says:

    @Florian,

    You can look at getting a VPS account somewhere and making sure the port you want to communicate on is open.

    Chad

  44. mark willis says:

    Thanks for the tip. I had been trying for a day to get a Perl server talking with a Flex XmlSocket but could not find a way to deal well with the zero delimiters in the stream. The xSocket library not only handles that easily, it provides a much more developer friendly model for socket interactions.
    Great tip!

  45. giorgio says:

    Thanks for the tip. A question: if I want to send an array of bytes from flash to java server, what kind of methods i must call in flash side and in java side?

  46. James says:

    Giorgio, I think you can send as String to Flex then use the split(‘#’) function or semi-colon if you like to convert it into an array. I did that for the DropDownList in Flex 4.

  47. James says:

    Hi, what is the code if I wanted to send a string from Jar to Flex?

  48. James says:

    Oh, I got a customize reply by editing the handler file.

  49. James says:

    Hi, how can I create a Java client that can send message to xsocket server?

  50. James says:

    Is this xSocket work for 1-1 or 1-to-many, I would like to see how I can create with 1-to-many scenario.

Comments are closed.