Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 26 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
26
Dung lượng
63,94 KB
Nội dung
< Day Day Up > UsingSocketServers 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. Usingsocket 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 usingsocket 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 this 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(); To 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) { trace(success); } server.onConnect = serverConnected; Here the serverConnected() function is called when the onConnect event is fired. The success parameter in the function definition has a value of true if the connection was successful and false if the connection was unsuccessful. The onXML event is used as follows: function xmlReceived (data:XML) { trace(data); } server.onXML = xmlReceived; The xmlReceived() function is called each time information arrives via the socket. The data parameter contains the XML document pushed into Flash. The onClose event handler can be defined and used as follows: function socketClosed () { //notify the user } server.onClose = socketClosed; You would typically use this type of event to let the user know that a connection has been lost. ElectroServer 3 To utilize the functionality of any socket server, you can't just upload a script into the CGI-bin of your Web site or place it in a normal Web-accessible directory. Usually written in Java, C, C++, or Visual Basic, socketservers generally require root-level access to the Web server. This usually means that you must be running your own dedicated 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. The 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 includes Macintosh OS X and higher, Linux, UNIX, Windows, and so on. For non–Windows installation instructions for ElectroServer 3 and the JRE, see http://www.electrotank.com/ElectroServer/ . The next exercise guides you through the steps to get ElectroServer 3 up and running on your Windows computer. 1. Download and install the JRE (for Windows) by going to http://www.java.com . This page will probably detect your operating system automatically. Click the download link. The Java software most likely will be installed automatically through the Web browser. 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. By 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 socketservers 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> <Action>Login</Action> <Parameters> <Name>myName</Name> <Password>myPassword</Password> </Parameters> </XmlDoc> ElectroServer 3 reads the Action node, and then knows what else to look for. When it sees that the Action is Login, it knows to expect a Name node and a Password node. You must use a specific XML protocol for every socket server. XML itself is a standard, but the structure of the XML is specific to the socket server being used. Does 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. To 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 ActionScript: ElectroServer.sendMessage("private", "Hello Derek!", "Derek"); NOTE Documentation for every method, property and event of the ElectroServer class can be found in a file named Class_Documentation.html in the directory Program Files\Electrotank\ElectroServer 3\Examples\Flash MX 2004 on your hard drive. To find the most up-to-date ElectroServer class and documentation, visit http://www.electrotank.com/ElectroServer/ . You can also download the ElectroServer 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. 1. 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! 2. With the Actions panel open, select Frame 1 of the Actions layer and add the following script: 3. 4. var es:ElectroServer = ElectroServer.getInstance(); 5. The ElectroServer class is a static class (also known as a singleton), which means that only one instance of it can exist within your movie. To create this instance of the ElectroServer class, simply call the getInstance() method directly on the class, and it will return a reference to itself. The line of code in this step creates a 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: 4. 5. es.setIP("127.0.0.1"); 6. 7. es.setPort(9875); 8. When you installed ElectroServer 3, it created default settings that it would use for its operation. Unless these settings are changed, when you start ElectroServer 3 it will bind to your local IP address (127.0.0.1) and listen on port 9875. The script above tells the ElectroServer class instance at which IP address to look for 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. [...]... 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: 1 Connect to ElectroServer 3 2 Log in to ElectroServer 3, which assigns you a username 3 Join a room In Step 4, we've scripted what happens... fired, it is passed three parameter values The first parameter, type, can be a value of either "public" or "private" In this exercise, all messages are public messages, so we don't need to worry about using that first parameter However, in a full-featured chat front-end you would want to know whether an arriving message was public or private If it's a private message, you might want Flash to play a... userListBox_lb.setDataProvider(userlist); 23 24 } 25 26 es.userListUpdated = showUsers; 27 28 showUsers(); 29 First we create a function called showUsers() This function grabs the most recent user list from the ElectroServer class using the getUserList() method and stores it as an array called userlist As a result, the userlist array will contain one object for each user in the room Each of these objects has a property named label... current list of users If we didn't call the showUsers() function manually, the current user list wouldn't display in the userListBox_lb instance until the next person came into the room or left the room, causing a userListUpdated event to fire 17 To show the list of rooms, add the following code: 18 19 function showRooms() { 20 21 var roomlist:Array = es.getRoomList(); 22 23 roomListBox_lb.setDataProvider(roomlist);... change event is fired whenever a user changes the selected room in the roomListBox_lb instance Usually, this is accomplished by the user's clicking a room in the list, although it can also be accomplished using the keyboard When the change event is fired, an Event object is passed into the event handler We extract the name of the item that was selected and give it a variable name of room The value of that... separate rooms and try to join a room by clicking the room name 21 Close the test movie and save your work as Chat2.fla You've accomplished a lot in this exercise You've created a basic chat application using the ElectroServer class, a little bit of ActionScript, and some components If you're interested in creating a more advanced chat room, look through the ElectroServer class documentation on the CD-ROM . < Day Day Up > Using Socket Servers A socket server is an application that can accept " ;socket& quot; connections. Socket connections are persistent,. 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