Flash Vista - Home
Newest Cool Site
The Two Tales
Site info | Archive
Main Navigation
Home
New Links
Top Rated
Most Popular
Cool Sites
Search

Flash Tutorials
Flash Resources
Flash News
Flash Templates
Flash Intro Templates
Website Templates
Flash Games
Flash Books
FlashVista Polls
Sitemap


Random Link
English
The Tree
Site info | Get another
FlashVista
Login
Register
Subscribe

Add Link
Modify Link
Favorites
Suggest Category

Advertise with us
Support us
Credits / Thanks
Contact

Flash Templates:

More Templates ...

Mailing List
User

Password



Register
Forgot password?
Partner websites
Flash Templates
Flash Components
Free Hit Counter
Free Seo Tools
Free Tutorials
Free Video Tutorials
Forum signatures
Other Resources
Suggest
Suggest this site to a friend


Mailing List
Status: Not logged in

English English German French Spanish Italian Portuguese Russian Polish Finnish Dutch Swedish Thai Romanian Traditional Chinese Simplified Chinese
SearchNot logged in
Keyword: Search for: Advanced Search


XML Sockets: the basics of multiplayer games


NEW Flash Tutorials in Video Format - Powered by LearnFlash.com: 45 minutes of flash tutorials now available in streaming format or download. Topics Include flash for beginners, text effects, actionscripting, audio/video, flash 8 and more.


Download the source file for this tutorial Printer version



by Marco Lapi, alias Lapo
www.gotoandplay.it


A QUICK INTRODUCTION TO SOCKETS

A socket is an endpoint for the communication between two machines over a network and it represents the base for client-server communication. Once a socket connection is established between these two, the client can access a "service" on the server machine. As an example, services can be an HTTP request (a web page) or an FTP request (file transer), etc...

Surfing the web is a nice example of this process: every time you connect to www.gotoandplay.it with your internet browser you establish a socket connection with a server machine and once this is done your browser can request a page to a specific service through a communication protocol called HTTP.

Services are also referred as "ports", and they represent distinct channels of communication that can be used by the client
and server to exchange data. Ports are described by a 16-bit integer value, which means you can virtually have a maximum of 65535 and among these the first 1024 are called "well known ports".
An example of these well-known-ports can be HTTP (80), FTP (21), POP (110), SMTP (25), TELNET (23), SSH (22), etc...

WHAT IS A SOCKET SERVER AND HOW IT WORKS

Multiplayer applications let you interact with other users in real-time thanks to a socket service specifically designed for the app/game functionalities. One of the simplest multiuser application I can think of is a chatting system: it mainly consists of a server-side socket service and a client application that sends and displays the user's messages.

Picture #1 explains this mechanism:



Picture 1


- the client connects to the server application;
- the user can receive messages from all other clients;
- every time the client sends a message, this is broadcasted on all the other clients connected.

THE CLIENT-SIDE: FLASH MX AND SOCKET COMMUNICATION

Flash MX has built-in support for socket connection with the XMLSocket object. This object lets you establish a communication channel with a socket server application and it is based around XML as a data-format for messages in both directions.

Creating an XMLSocket object in actionscript is very simple:


mySocket = new XMLSocket()


By inspecting the Flash MX reference you'll see that only 3 methods are available for this object:

  1. connect(host, port) = tries to connect to the specified host on the port number specified;
  2. send(xmlObj) = sends and XML Object to the server;
  3. close() = shuts down the connection.


Also four events are provided for the XMLSocket Object:

  1. onConnect = this is fired when the connection is established with the server;
  2. onData = when some data is received this handler automatically invokes the onXML event; this feature is discussed later in the article;
  3. onXML = invoked when and XML Object is sent to the client; the XML Object must be terminated with a 0 byte, otherwise the event won't fire;
  4. onClose = fired every time the connection is closed by the server.
    By using the XMLSocket object and providing the functions that handle the object events you can start experimenting with the beautiful world of instant messaging and multiuser games/applications.

Before diving into a fully functional example, we need to see what happens on the other endpoint, the server.

THE SERVER-SIDE

Flash is a great tool for developing multiuser applications, but it must be paired with some other technologies to implement the server-side part of the system.

The choice here is not simple as there are really many different languages that could be employed to accomplish this task: C++, Java, C#, Python, Perl, Visual Basic, standalone PHP, and many more...

However one of the most common option is Java for a number of reasons: first of all it is very well known for its portability and this means that your Java application can be executed on a number of different operating systems without changing one single line of code!
Also Java has proved to be highly stable and its performance is really good, making it a good candidate for this job.

Here follows an example of a very simple java socket connector that acts as a sever:


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


public class simpleServer
{
public static void main(String args[])
{
// Message terminator
char EOF = (char)0x00;

try
{
// create a serverSocket connection on port 9999
ServerSocket s = new ServerSocket(9999);

System.out.println("Server started. Waiting for connections...");
// wait for incoming connections
Socket incoming = s.accept();

BufferedReader data_in = new BufferedReader(
new InputStreamReader(incoming.getInputStream()));
PrintWriter data_out = new PrintWriter(incoming.getOutputStream());

data_out.println("Welcome! type EXIT to quit." + EOF);
data_out.flush();

boolean quit = false;

// Waits for the EXIT command
while (!quit)
{
String msg = data_in.readLine();

if (msg == null) quit = true;

if (!msg.trim().equals("EXIT"))
{
data_out.println("You sayed: "+msg.trim()+""+EOF);
data_out.flush();
}
else
{
quit = true;
}
}
}
catch (Exception e)
{
System.out.println("Connection lost");
}
}
}


If you have some basic Java knowledge it shouldn't be difficult to grasp the concepts in this example.
I'll try to make it even clearer for you:

a new ServerSocket is instantiated and port 9999 is used for communication;
using s.accept() the application stops and waits for an incoming connection;
when a client connects, two objects are created for handling input and output on the Socket (data_in, data_out);
a welcome message is sent to the client;
a loop is established so that every message sent by the user is sent back to prove that the server is working;
if the client sends the string "EXIT" the loop stops and the server quits.
Even if you're not familiar with the Java language and its API, it should be clear what is going on behind the scenes and you could try to implement it using a language you're more comfortable with.

BACK TO THE CLIENT-SIDE

Now that we know what is happening on the server we can build a simple Flash client.

Figure #2 shows the client prototype at work.



Picture 2


On the stage we have 3 UI components:

an html dynamic text area to show messages;
an input text for the user messages;
a send button.
Here is the actionscript code for this prototype:


mySocket = new XMLSocket();

mySocket.onConnect = function(success)
{
if (success)
msgArea.htmlText += ";Server connection established!"
else
msgArea.htmlText += "Server connection failed!"
}

mySocket.onClose = function()
{
msgArea.htmlText += "Server connection lost"
}

XMLSocket.prototype.onData = function(msg)
{
trace("MSG: " + msg)
msgArea.htmlText += msg
}

mySocket.connect("localhost", 9999)

//--- Handle button click --------------------------------------
function sendMsg()
{
if (inputMsg.htmlText != "")
{
mySocket.send(inputMsg.htmlText + "n")
}
}


The onConnect method checks if the connection was succesfully established and outputs a message. The onClose method shows some text if the communication is lost.

The next lines need a bit more of explanation: the onData method is overridden in the XMLObject itself by accessing its prototype. This is a common OOP (Object Oriented Programming) technique that is useful when you need to redefine the behaviour of a public method.

If you recall we said that the onData event calls the onXML method by default, but in this specific case we are not dealing with XML messages but with simple strings, so we don't need to treat them as an XML object.

By overriding the method in the XMLSocket prototype we can create our custom actions to handle data coming from the server, and in this case the method simply writes the strings to the dynamic text area.

To connect to the server we just used: mySocket.connect("localhost", 9999), assuming that the server application is running on the same machine of the client and passing the same port number we used in the Java code.

WHERE IS XML?

We've been talking about exchanging XML messages between client and server, but we ended up using simple strings... so where's the catch?

Actually the XMLSocket Object can be used to transfer data formatted in ways other than XML and choosing the right format is strongly related with the architecture of the application you want to build.

XML is very popular and platform independent, making it one of the best choices for a wide range of applications. It is also very simple to debug and maintain. However when dealing with multiplayer games your attention should also be focused on performance and an XML document can sometimes be too heavy for games that require a fast interaction.

I am not saying XML is bad for multiplayer games, and many free and commercial servers do use it as a communication protocol. XML can be properly optimized so that bandwidth is preserved. By doing so you can still retain it's flexibility and ease of use and also you don't have to write a parser from scratch.

On the other hand it can also be possible to compress information in special string formats or even binary data: this will surely improve performance and save bandwidth at the cost of more complex coding.

SOME NOTES ABOUT THE SECURITY

The XMLSocket object respects the sandbox security protocol built in the Flash player. This means that a Flash client will be able to connect only to socket servers that reside on the same host from which you downloaded the SWF application.

A note about firewalls: since Flash only allows port numbers higher than 1024 for XMLSockets, is very likely that a firewall between the client and server will filter the data packets you're trying to send. If you have a personal firewall installed you should check its policies and configure it so that it allows traffic from and to the server port.

CONCLUSIONS

Since these topics may not sound familiar to many Flash developers I'd like to suggest you to analyze the code presented in this article and try to experiment a bit with it.

It is possible to expand these simple examples we presented here by adding a custom communication protocol for your application. Once the message format is defined (using XML for example) you can start adding a simple XML parser in the client to process the requests and handling the new features.

More info and questions can be discussed in our Forums

If you want to experiment with the Java code you can freely download the Java SDK.

Here are some links to popular multiuser servers for Flash:


Flash Communication Server

Electro Server

Unity

Oregano

Jabber

Swocket

FlashNow

Xadra


Some other XMLSockets resources on the web:


http://www.macromedia.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary860.html

http://www.devshed.com/Client_Side/Flash/XMLSockets/page1.html

http://home.earthlink.net/~ymcvicar/tutorials/faqs/flashxml/

http://www.heliant.net/~stsai/code/


Happy programming!



(Added: 02-18-2004, Hits: 0, Rating: 3.74, Votes: 50, Reviews: 19)
Add to Favorites Suggest to a Friend

Reviews: (10)

Hi everyone, I'm making a online multiplayer game and if you just try you will get it because I am. I'm 11 years old and I can do that stuff. its accually quite simple. All you need is a few scripts that are probably somewhere in the internat really since I know from my expiriences!
(Added: 02-24-2007 User: Guest)

People, what the hell, those are questions not reviews. Go find other tutorials and quit bothering this guy.

This tutorial is excellent as far as a simple, straight-forward guide to explaining sockets on the flash side. It does open a lot of questions about the server stuff, since without a server opening a socket is not possible. But I guess that's why you provided links to other resources!

Thanks!

(Added: 01-30-2007 User: Guest)

I dont really understand the server side but for a person running around u would just send numbers which represent _X and _y. If anyone understands the server side please email me at ben9@san.rr.com
(Added: 01-28-2007 User: Guest)

[Lee] I'm sure this is a good tutorial, but I have no idea how to make the scripts/server side program run constantly on my website's server. If anyone has figured out how to do this or has gotten this to work PLEASE email me at DC@xaranda.net!!
(Added: 12-04-2006 User: Guest)

hey, im still confused. I downloaded the sorce file and it said that the conection failed. How would i be able to make a conection? Do i have to download one of those multiuser servers?
(Added: 10-17-2006 User: lancerawks)

Im compleatly new to this all, could you show me it all in more detail?
(Added: 10-17-2006 User: lancerawks)

I have download the example. run the client in flash however it says server connection failed. i guess this is because i have not run the server but how do you do that? when opening the folder the .java file is not reconised as flash
(Added: 10-03-2006 User: Guest)

how do you make like user names?
like for a game?
(kilgore_scott@hotmail.com)

(Added: 09-22-2006 User: Guest)

good but how would you create a multiplayer thing where you move around and can see each outher moving around?
(Added: 08-09-2006 User: Guest)

How can I use this on a remote server?
(Added: 07-13-2006 User: Guest)


Add Review
Please note:
We review EVERY comment before it appears on the site, so please dont waste your time by posting spam links :)
No URLs allowed, no HTML please.

If you register or login first, your review will contain your nickname


Rate It



Excellent!
Very Good
Good
Fair
Poor