Home : Contact Us : Site Map : Search

ad’s by Google
 

Flash Communication with Java and
Flash Communication with Flash
via Sockets

In a project, I had a need to have a flash application communicate with another flash application on another computer in an intranet. There is a good overview of networking and communications techniques here.

In my situation, the simplest solution was to use socket communication via XMLSockets. However, Flash can’t communicate directly with another Flash app via sockets - it has to go through a server. Rather than going for a more complex server like Flash Communication Server or Unity, I thought I would use a simple Java Socket Server.

So I made a simple Flash Socket app based on this page, and used the Adobe sample code for a Java Socket Server here. It accepts incoming connections and displays the received messages in the command  prompt window. By default, a new server is created on port 8080 of your local  machine, although you can specify a different port number when starting your  server from the command line.

Unfortunately, there were considerable problems in the Adobe sample code, so I spent the better part of my day fixing it. It now works great, and easier to understand for a novice. I have pasted it beolw:

import java.io.*;
import java.net.*;

class SimpleServer
{
   private static SimpleServer server;
   ServerSocket socket;
   Socket incoming;
   BufferedReader readerIn;
   PrintStream printOut;

   public static void main(String[] args)
   {
       int port = 9001;

       try
       {
           port = Integer.parseInt(args[0]);
       }
       catch (ArrayIndexOutOfBoundsException e)
       {
           // Catch exception and keep going.
       }

       server = new SimpleServer(port);
   }

   private SimpleServer(int port)
   {
       System.out.println(">> Starting SimpleServer2"); // Sent to console
       try
       {
           socket = new ServerSocket(port);
           incoming = socket.accept();
           // Waits here until connection is established
           readerIn = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
           printOut = new PrintStream(incoming.getOutputStream());
           out("Enter EXIT to exit."); // Sent to Socket AND console
           boolean done = false;
           while (!done)
           {
               String str = readerIn.readLine();
               if (str == null)
               {
                   done = true;
               }
               else
               {
                   str = str.trim();
                   System.out.println("input: [" + str + "]\r"); // Sent to console
                   out("Echoing Back: " + str); // Sent to Socket AND console
                   if(str.trim().equals("EXIT"))
                   {
                       done = true;
                   }
               }
           }
           incoming.close();
       }
       catch (Exception e)
       {
           System.out.println("End Exception: " + e); // Sent to console
       }
   }

   private void out(String str)
   {
       printOut.println(str + "\u0000"); // Sent to Socket
       System.out.println("output: [" + str + "]"); // Sent to console
   }
}

If you want to play with it, create a new text document and paste the above code into it. Save the document to your hard disk as SimpleServer.java and compile it using a  Java compiler, which creates a Java class file named SimpleServer.class. If you don't have a Java SDK installed, they can compile their .java file online here.

You can start the XMLSocket server by opening a command prompt and typing java SimpleServer. The SimpleServer.class file can be located anywhere on your local computer or network; it doesn't need to be placed in the root directory of your web server. (NOTE: If you're unable to start the server because the files are not located within the Java classpath, try starting the server with java -classpath . SimpleServer.)

 

If you are interested, I have also pasted below the AS2 code I used to make the corresponding Flash App (sorry about the formatting - the tabs got stripped out). Simply paste this code into the actionscript area of the first frame of an ActionScript 2 project and compile. But note, you will have to run the app from outside of the Flash Development Environment.

createSocket ();

function createSocket () {

// Set up the GUI
_root.createTextField("inputlabel",4,20,20,50,20);
inputlabel.text = "Input:";
_root.createTextField("outputlabel",5,20,50,50,20);
outputlabel.text = "Output:";
_root.createTextField("tracelabel",6,20,80,50,20);
tracelabel.text = "Tracer:";
_root.createTextField("inputer", 3,70,20,200,20);
_root.createTextField("outputer",2,70,50,200,20);
_root.createTextField("tracer",  7,100,80,400,300);
outputer.type = "input";
outputer.border = true;
inputer.border = true;
tracer.border = true;

// Set Up the Comms
serialServer = new XMLSocket ();
//trace ("made it" + serialServer);
tracer.text = tracer.text + "made it" + serialServer + newline;
//127.0.0.1 is the same as "localhost" ie an alias to your local machine
//it is concievable to that you would want to connect from another machine and you would change this
serialServer.connect ("127.0.0.1", 9001);
serialServer.onConnect = function (success) {
//trace ("connected " + success);
tracer.text = tracer.text + "connected " + success + newline;
serialServer.send ("HOWDY FROM FLASH " + new Date().toString() + newline);
};
serialServer.onClose = function () {
//trace ("closed");
tracer.text = tracer.text + "closed" + newline;
};
serialServer.onData = function (data) {
//trace ("incoming: " + data);
//tracer.text = tracer.text + "[0]=" + data.charCodeAt(0) + newline;
//tracer.text = tracer.text + "[1]=" + data.charCodeAt(1) + newline;
if (data.charCodeAt(0) == 13 && data.charCodeAt(1) == 10) {
data = data.slice( 2, data.length+1 );
}
tracer.text = tracer.text + "incoming: " + data + newline;
inputer.text = inputer.text + data;
};
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
//trace("For the last key typed, Key code is: " + Key.getCode() + ",ASCII value is: " + Key.getAscii() + newline);
//tracer.text = tracer.text + "For the last key typed, Key code is: " + Key.getCode() + ",ASCII value is: " + Key.getAscii() + newline;
if (Key.getCode()==13) {
serialServer.send (outputer.text + newline);
//trace ("output: " + outputer.text);
tracer.text = tracer.text + "output: " + outputer.text + newline;
outputer.text = "";
}
};
Key.addListener(keyListener);

}

 

I hope you find that useful. From here, it is reliatively easy to make the Java Socket Server open another connection to the other Flash app and simply pass input from one flash app out to the other. In this way you could connect two or more flash applications togeather. I have pasted more example code below. The flash apps can be the same as above, except have different versions that connect to different ports (9001, 9002, 9003). The multi-client version of the Java Socket Server is below:

import java.io.*;
import java.net.*;

class SimpleServer
{
   private static SimpleServer server;
   ServerSocket socket1;
   ServerSocket socket2;
   ServerSocket socket3;
   Socket incoming1;
   Socket incoming2;
   Socket incoming3;
   BufferedReader readerIn1;
   BufferedReader readerIn2;
   BufferedReader readerIn3;
   PrintStream printOut1;
   PrintStream printOut2;
   PrintStream printOut3;

   public static void main(String[] args)
   {
       int port = 9001;

       try
       {
           port = Integer.parseInt(args[0]);
       }
       catch (ArrayIndexOutOfBoundsException e)
       {
           // Catch exception and keep going.
       }

       server = new SimpleServer(port);
   }

   private SimpleServer(int port)
   {
       System.out.println(">> Starting SimpleServer3"); // Sent to console
       try
       {
           socket1 = new ServerSocket(port); // can't use a port already used
           incoming1 = socket1.accept(); // Waits here until connection is established
           readerIn1 = new BufferedReader(new InputStreamReader(incoming1.getInputStream()));
           printOut1 = new PrintStream(incoming1.getOutputStream());
           printOut1.println("Enter EXIT to exit." + "\u0000"); // Sent to Socket
           System.out.println("output: [Enter EXIT to exit.]"); // Sent to console
           printOut1.println("connection 1 established" + "\u0000"); // Sent to Socket
           System.out.println("output: [connection 1 established]"); // Sent to console

           socket2 = new ServerSocket(port + 1); // can't use a port already used
           incoming2 = socket2.accept(); // Waits here until connection is established
           readerIn2 = new BufferedReader(new InputStreamReader(incoming2.getInputStream()));
           printOut2 = new PrintStream(incoming2.getOutputStream());
           printOut1.println("connection 2 established" + "\u0000"); // Sent to Socket
           System.out.println("output: [connection 2 established]"); // Sent to console
           printOut2.println("connection 2 established" + "\u0000"); // Sent to Socket
           System.out.println("output: [connection 2 established]"); // Sent to console

           socket3 = new ServerSocket(port + 2); // can't use a port already used
           incoming3 = socket3.accept(); // Waits here until connection is established
           readerIn3 = new BufferedReader(new InputStreamReader(incoming3.getInputStream()));
           printOut3 = new PrintStream(incoming3.getOutputStream());
           out("connection 3 established"); // Sent to Socket AND console

           boolean done = false;
           while (!done)
           {
               String str = readerIn1.readLine(); // Waits here until reads something - BAD - can't do multi-client
               if (str == null)
               {
                   done = true;
               }
               else
               {
                   str = str.trim();
                   System.out.println("input: [" + str + "]\r"); // Sent to console
                   out("Echoing Back: " + str); // Sent to Socket AND console
                   if(str.trim().equals("EXIT"))
                   {
                       done = true;
                   }
               }
           }
           incoming1.close();
           incoming2.close();
           incoming3.close();
       }
       catch (Exception e)
       {
           System.out.println("End Exception: " + e); // Sent to console
       }
   }

   private void out(String str)
   {
       printOut1.println(str + "\u0000"); // Sent to Socket
       printOut2.println(str + "\u0000"); // Sent to Socket
       printOut3.println(str + "\u0000"); // Sent to Socket
       System.out.println("output: [" + str + "]"); // Sent to console
   }
}

 

 

::Home:: ::About Us:: ::Solutions:: ::Resources:: ::Seminar Videos:: ::Digital IP:: ::Tech for Art:: ::PodCasting:: ::VodCasting:: ::Audio Clips:: ::Naming and Filing:: ::Portable Storage:: ::Router Config:: ::Tech Tips:: ::Convert WMV:: ::Best Online Video:: ::Flash to Java:: ::Links:: ::Search::

Except where otherwise noted, this site is licensed from MindSpace SolutionsTM Limited under a Creative Commons Attribution-NonCommercial 2.5 License