< Day Day Up > Using Socket Servers A socket server is an application that can accept "socket" connections.. A key principle to understand about using socket connections with Flash is t
Trang 1< Day Day Up >
Using Socket Servers
A socket server is an application that can accept "socket" connections Socket
connections are persistent, which means that they let you remain connected to a server rather than making a connection just long enough to download information before
disconnecting Unlike a scripted page, a socket server is an application that's always running It can accept simultaneous connections from multiple computers and exchange information among them While you're connected to a socket server, you can send or receive information at any time Using socket connections to continually transfer data to and from the server is how most chats and multiplayer games are created in Flash
A key principle to understand about using socket connections with Flash is that you don't have to request information to get information—for example, in a chat application a message can be pushed into Flash at any time without Flash having to ask for it
Introduction to the XMLSocket Class
This section provides a basic introduction to Flash's built-in XMLSocket class This discussion is simply a guide to the use of this built-in class, so you can familiarize
yourself with the general concepts needed for plugging your applications into nearly any socket server The exercise that follows makes use of a special socket server that wraps most of the functionalities you're about to learn into a simple-to-use object But more on
Trang 2this in a bit Let's look at the inherent way Flash communicates with a socket server Before you can connect a Flash movie to a socket server, you must create a new
XMLSocket object, using the constructor for the XMLSocket class You can then use the methods of the object to connect to a server and exchange information In this section, we'll show you how to create and use an XMLSocket object while also using the XML class methods and properties introduced earlier in this lesson
To create a new XMLSocket object, you must use the constructor for XMLSocket Here's
an example:
var server:XMLSocket = new XMLSocket();
This line of ActionScript creates a new XMLSocket object named server To connect the XMLSocket to a server, you simply employ the connect() method using the following syntax:
server.connect(hostName,port)
The hostName parameter is the IP address on which the socket server resides—usually a numeric sequence (for example, 65.134.12.2) IP addresses such as 127.0.0.1 or localhost are valid references to your own computer If you type http://localhost into your Web browser's address bar, it would try to connect to your computer as if it were a Web site The port parameter refers to the port on which the server is listening Flash can only connect to ports higher than 1024 For example:
var server:XMLSocket = new XMLSocket();
server.connect("localhost", 9999)
You can close a connection with a socket by using the close() method:
server.close();
Trang 3To send information via the socket connection, simply use the send() method and pass in the object you want to send For example:
server.send("<Text>Hi</Text>");
The XMLSocket class can respond to the following types of events:
• onConnect— This event fires when the connection is accepted or fails
• onXML— This event fires when information arrives via the socket connection
This action lets you know that new information has arrived so that you can use it
• onClose— This event fires when the connection with the socket is lost This event
will not fire as a result of purposely closing the connection from Flash using the XMLSocket.close() method
As we did with the onLoad event in the XML class, we have to define these event
handlers with the XMLSocket object that we create For example:
function serverConnected (success:Boolean) {
The onXML event is used as follows:
function xmlReceived (data:XML) {
Trang 4dedicated server in order to install and use a socket server Fortunately, this isn't as scary
as it sounds As a matter of fact, you can set up a socket server on your own personal computer so that you can develop with it, which is a recommended and common practice when developing applications that use a socket server
For the next exercise, we'll show you how to get a socket server up and running on your local machine so that you can go on to build a simple chat application that connects to the socket server To test it, you'll need to use Windows 98, Windows 2000, Windows XP, or Windows ME
Trang 5The accompanying CD-ROM contains the installer for a Java-based socket server called ElectroServer 3 You need to have Java 2 Runtime Environment (JRE) version 1.4.1_02
or higher installed on your machine to run ElectroServer 3, as well as to test the chat program you build in the next section
NOTE
ElectroServer 3 is supported by any operating system that supports the JRE This includesMacintosh OS X and higher, Linux, UNIX, Windows, and so on For non–Windows installation instructions for ElectroServer 3 and the JRE, see
ElectroServer 3 will not run properly with a version of the JRE older than
1.4.1_02
2 To install and start ElectroServer 3 on Windows, open the Lesson12/Assets
directory Double-click the file called InstallElectroServer.exe to install
ElectroServer 3, and follow the series of prompts to completion You don't need to change any of the default options during the installation process
You have just installed ElectroServer 3, the socket server that we'll use in the next exercise to build a Flash chat If you left the default options selected while
installing ElectroServer 3, then it also installed several example files onto your
hard drive
3 To start ElectroServer 3, click Start > All Programs (or Program Files) >
Electrotank > ElectroServer 3 > Start ElectroServer
If you installed the JRE properly, ElectroServer 3 should have started without any problem
Trang 6By default, ElectroServer 3 will connect to the 127.0.0.1 IP address, which is the
IP address by which your computer refers to itself Also, the default port on which ElectroServer 3 will exchange data is 9875 Both the IP and the port are
configurable, but you won't need to change the settings for the chat exercise
At least a dozen socket servers have been created for use with Flash Among them, here are the most popular (not in order of popularity):
o ElectroServer 3 (www.electrotank.com/ElectroServer/) is a full-featured socket server that was created specifically to meet the needs of multi-user Flash game developers As such, it has features (not seen in other socket servers) that appeal to Flash game programmers
o Macromedia Flash Communication Server (www.macromedia.com) is not a socket server, although it's similar to one It uses a proprietary data-
exchange protocol developed by Macromedia It can be used to accomplish tasks such as video and audio transfer (for video chatting)
o Unity (www.moock.org/unity/) is a general socket server that can be used
to create any number of multi-user applications, including chat and games
The ElectroServer Class
In the next exercise, you'll build a chat program that communicates with ElectroServer 3 When being developed, a socket server must be programmed to look for a certain
protocol XML is a protocol, but even deeper than that, the socket server must look for XML in a certain structure—a protocol within a protocol For example, if you want to send an XML-formatted login request from Flash to ElectroServer 3, it must use this format:
<XmlDoc>
Trang 7Does this sound daunting? You can send or receive 100 or so different XML packets in ElectroServer 3 to accomplish tasks such as sending a message, creating a room, and so
on There is good news, though: the ElectroServer class is included with this lesson The ElectroServer class internally handles all of the XML formats that need to be sent or received You can talk to ElectroServer 3 easily through the ElectroServer class, without having to write a single line of XML
NOTE
Within the directory of this project's lesson files is a file named ElectroServer.as This file defines the ElectroServer class and its capabilities During export or compiling of this movie, Flash uses the contents of this file to enable the exported movie to utilize the functionality of the ElectroServer class It's important that this file (and its supporting files, named Wddx.as and WddxRecordset.as) exist in the same directory as the
completed project file; otherwise, an error will occur when you export the movie
Trang 8To send a chat message to the server, this is all you need to do:
ElectroServer.sendMessage("public", "Hello world!");
This line of ActionScript executes the sendMessage method of the ElectroServer class The first parameter, "public", tells the ElectroServer class to send a public message to the entire room The second parameter is the message to send
To send a private message to a user named Derek, you would use this line of
class as a Flash extension so that you can use the Actions panel to browse the
ElectroServer class and access help on it, just as with all other Flash classes
It's time to build a simple chat application using ElectroServer 3 A few more basic concepts as well as specific methods and events of the ElectroServer class will be
discussed as we go along
Trang 91 Open Chat1.fla in the Lesson12/Assets folder
The file contains four layers: the Actions layer, where we'll keep the ActionScript; the Labels layer, which contains the labels for the movie; the Assets layer,
containing the text fields and buttons; and the Background layer, which contains the interface graphics
We'll begin by scripting the code to get a user connected to ElectroServer 3,
logged in, and joined to a room A room is nothing more than a collection of users When a user sends a chat message, it's automatically sent to everyone in the room ElectroServer 3, like most socket servers, supports multiple rooms Many rooms can exists at once, each with users A user can switch from one room to another, as you'll see later in this exercise
After we've scripted our project to the point where a user can log in and join a room, we'll add the ActionScript needed to display the user list, room list, and
allow the user to chat All of this can be done in about 80 lines of code!
Trang 102 With the Actions panel open, select Frame 1 of the Actions layer and add the following script:
variable named es, which is our reference to the instance of the ElectroServer class
For the rest of this exercise, the ElectroServer class will be accessed by using the
es reference created in this step
NOTE
We're able to create an instance of the ElectroServer class only because of the ElectroServer.as file that exists in the same directory as this project file This as file is loaded during the process of exporting the project file SWF, enabling all the functionality of the ElectroServer class that we'll script in the following steps
3 Using the following code, set the IP and port to which the chat should connect:
ElectroServer 3, and which port at that IP it should use
The ElectroServer class will not attempt to connect to ElectroServer 3 until you
invoke the connect() method We'll do that later in the exercise
Trang 114 With the same frame selected, add the following code to capture the connection response from ElectroServer 3:
In a moment, we'll create the script that connects our application to ElectroServer
3 When the connection happens, an onConnection event occurs, which is what this script handles Two parameters are passed to the function when the
onConnection event is fired: success and error
The first parameter, success, is a Boolean value If true, the connection was a success and the user is taken to the Login frame label to log in If false, the
connection failed If the connection failed, the second parameter, error, is passed
to the function This parameter contains a string that explains what went wrong When a failed connection occurs, the else part of the statement is executed This part of the statement displays the error message in the text field named msg_txt This text field exists at the Connecting frame label on the timeline To understand how this works, it's important to realize that one of the last scripts we will place on this frame (in Step 9) will move the timeline of our application to the Connecting frame label, where it will wait for a response from the server If an error occurs, the part of our script that reads:
msg_txt.text = error
Trang 12will display the error message in the msg_txt text field on the Connecting frame label because our application is paused at that label
What can cause the connection to fail and what kind of error messages are
generated? If the connection failed because the ElectroServer class could not find ElectroServer 3 (possibly due to a wrongly specified IP or port, firewall issues, or the fact that the server was not running), error will contain a string that reads, Could not establish a server connection Otherwise, an error will be generated dynamically from the server The server could deny a connection because it has reached its connection limit, which is 20 simultaneous users in the free license version
Before proceeding further, take a look at the essential steps necessary for chatting using ElectroServer 3 The user must do the following successfully:
the process of joining a chat room
5 Add the following script to capture the login response:
Trang 13On the frame labeled Login, which will be covered later in this exercise, the user
is allowed to enter a username and a room name, and click a button to send a login request to the server The server will then send back a response either allowing or denying the login request The loggedIn event is triggered when the server
responds to a login request
Similar to the onConnection event, the loggedIn event has two parameters: success and error If success is true, the login attempt was successful and the joinRoom() function is called If success is false, the login attempt was not successful and an error string is placed in the msg_txt field A user might receive an error if
attempting to log into the server with a username that's already being used
6 Add the following function to handle joining a user to a room:
Trang 14As shown in Step 5, when the login response from the server is a success, the joinRoom() function is called and the room that was specified by the user in the login screen is created Here's how
There are two methods of the ElectroServer class that are appropriate to mention here—createRoom() and joinRoom() The joinRoom() method tells ElectroServer
3 that you want to join a specified room Here's an example:
es.joinRoom("Sports");
If a room called Sports exists, you will join it If it doesn't exist, an error will be returned by the server This error is captured in the roomJoined event, which we'll script in the next step