Publishers of technology books, eBooks, and videos for creative people

Home > Articles

  • Print
  • + Share This
This chapter is from the book

Hello World

What better first application to write than hello world? It’s about time we write a little code!

In this section, we will introduce you to the ElectroServer API, and then use that to connect to ElectroServer, log in, and send a private chat message.

The ElectroServer API

The ElectroServer API is an ActionScript 3 API used by a multiplayer application to connect to and communicate with ElectroServer. The API is provided as a SWC file, which you will find it in the ‘lib’ directory of all examples in this book that communicate with ElectroServer.

The ElectroServer API allows the client to establish a connection with the server and then communicate with the server. It also does some amount of automatic management of data. For example, the API keeps track of which rooms you are currently in as well as the user list in each of those rooms.

There are three main types of messages that can travel in either direction between the client and the server:

  • Requests—Objects created by the client and then sent to the server. For instance, when you want to log in, you create a login request, and send that to the server. For all intents and purposes, anything that the client sends to the server is a request.

  • Responses—Objects created by the server as a result of a request and then sent to the client. For instance, once the server receives a login request from a client, it processes the request and generates a login response. This response would contain information such as whether or not the login was successful.

  • Events—Messages (sent from the server to a client) that did not necessarily originate from a request. For example, receiving a chat message in a chat room is an event. That chat message may have been generated by that same user, another user, or even by the server itself.

Most of what you can do with the API is request-driven. The client creates a request object of some type, populates it with information, and then sends it to the server.

Writing Your First Chat

In this section, we look at the example you’ll find in book_files/chapter4/hello_world.

Open the project file. Using the project tab, browse and open the Main.as class file. This is the only class file used in this project. There are no visual assets needed to compile this project. The only thing that you can see is a text field, created using ActionScript.

Compile the application to see what it looks like. Make sure ElectroServer is running. You should see something that looks like the screen below.

The compiled application will run through the following steps:

  • Prepares an ElectroServer instance to be used
  • Connects to ElectroServer on 127.0.0.1 and port 9899
  • Logs in with a random username
  • Sends a private chat message to itself, and captures that message

Each step of the way, the application logs what is going on to a text field on the screen.

Prepare an ElectroServer instance

The first thing you need to do before connecting to ElectroServer is create a new instance of the ElectroServer class. The ElectroServer class is the gateway to the entire API.

On line 36 of the Main class, you can see the creation of the new ElectroServer instance:

_es = new ElectroServer();

Since we will be using this class instance from other functions later, it is a class-level property.

Now that the ElectroServer instance exists, we add event listeners, so that we can capture the responses and events that come back from the server:

_es.addEventListener(MessageType.ConnectionEvent,
→"onConnectionEvent", this);
_es.addEventListener(MessageType.LoginResponse,
→"onLoginResponse", this);
_es.addEventListener(MessageType.PrivateMessageEvent,
→"onPrivateMessageEvent", this);

The first line establishes an event listener for the connection event. When a connection occurs or times out, the onConnectionEvent function is executed. Likewise, the next two lines establish event listeners for logging in and for private chat messages. They will be discussed further below.

Each of the addEventListener function parameters is worth discussing. First is the MessageType class. That class is used to store references to every request, response, and event type that is possible with the API. When adding an event listener, you use the MessageType class to point to the response or event that you want to capture.

The second parameter is a string that contains the name of the function you want to be called when the event occurs. This one item is something that is not ideal about the ElectroServer API; the code base for the API is maintained in ActionScript 2 to support older clients, and ActionScript 3 up-conversion code is used to generate the ActionScript 3 version of the API. Having to use a string function name when adding an event listener is an unfortunate side effect of that process. However, it doesn’t slow down code or present any problems other than the lack of compile-time checking of the function names used.

The third parameter describes the scope in which the function exists.

Connect

Now that the ElectroServer class instance exists and has the proper event listeners added, we can actually do something—connect! ElectroServer supports several different protocols (text, binary, HTTP, and RTMP). We’ll use binary throughout the entire book; it’s the best choice for our purposes because it is lightweight and fast.

So first, we tell the API which protocol we want to use on line 44:

_es.setProtocol(Protocol.BINARY);

Next, we make the connection attempt to ElectroServer, on line 47:

_es.createConnection("127.0.0.1", 9899);

Assuming all of the default ElectroServer settings are being used, and it is running, then this makes ElectroServer listen for socket connections at the local IP address of 127.0.0.1 on port 9899.

When the connection succeeds or fails, the onConnectionEvent function is called:

public function onConnectionEvent(e:ConnectionEvent):void {
  if (e.getAccepted()) {
       log("Connection accepted.");

       //build the request
       var lr:LoginRequest = new LoginRequest();
       lr.setUserName("coolman" + Math.round(10000 *
       →Math.random()));

       //send it
       _es.send(lr);

       log("Sending login request.");
  } else {
       log("Connection failed. Reason: " + e.getEsError().
       →getDescription());
  }
}

Notice the ConnectionEvent parameter passed into this function. All events and responses have typed objects passed in that contain information about what happened.

In the if statement, you can see that this event object contains a Boolean value indicating whether the connection was successful or not. If the connection was not a success, then we log that, and then log the error that describes why the connection failed.

If the connection was successful, we log that it was a success, and then attempt to log in to the server.

Login

By default, ElectroServer will allow a user to log in with any username—provided that it is unique (no one else already has that name) and that it passes the default vulgarity test included as part of the application. (Try replacing the username with profanity, and you will see an error logged.)

To log in to ElectroServer, first a LoginRequest object is created, a username is populated onto that object (a random name, in this case), and then this request object is sent to the server. All requests are handled in this way: create the request, populate it with information, and send to the server.

The server processes this request and sends back a login response. This response is captured in the onLoginResponse function:

public function onLoginResponse(e:LoginResponse):void {
  if (e.getAccepted()) {
       log("Login accepted. Logged in as " + e.getUserName());

       //create the request
       var pmr:PrivateMessageRequest =
       →new PrivateMessageRequest();
       pmr.setUserNames([e.getUserName()]);
       pmr.setMessage("Hello World!");

       //send it
       _es.send(pmr);

       log("Sending myself a private message.");
  } else {
       log("Login failed. Reason: " + e.getEsError().
       →getDescription());
  }
}

If the login was accepted, then the getAccepted() method of the LoginResponse object returns true. If it was not accepted, then we log that information, and then log the error description about why it failed.

If the login is successful, then we send a private message to our own user.

Send a private message

To send a private message with ElectroServer, you first create a SendPrivateMessageRequest object. This object is then populated with information such as the list of usernames it should go to, and the message payload. In this example, you’ll see that the list of usernames is an array of just one name, our own.

The server processes this request and ends up sending private message events to all users in the list. A private message event in this example is captured by the onPrivateMessageEvent function:

public function onPrivateMessageEvent(e:PrivateMessageEvent):
→void {
  log("Private message received from " + e.getUserName() +
→". Message: " + e.getMessage());
}

In this function, we simply log that a private message was received, who it was from, and the message itself.

  • + Share This
  • 🔖 Save To Your Account