Plugins

From EsWiki

(Redirected from Plug-in tutorial)
Jump to: navigation, search

A plug-in is the most generic and flexible way to add functionality to ElectroServer. Simply put, a plug-in is a piece of code that can be tied to the server itself or a room and can then be called via clients to directly ask it to perform an action. As a special case, room-level plug-ins have the ability to listen to many events that occur in a room such as room variable changes or public messages. These are the bread and butter of multi-player game development.

Contents

Example Plug-ins

Finding the Java source code

There are several example plug-ins in the examples folder for ElectroServer 4, all named starting with "Plugin". Take a look at the PluginUserEnterAndExit folder in particular. The code for the plug-in is found in the PluginUserEnterAndExit.java file. Browse to find it, starting in your ElectroServer 4 folder, then opening \examples\PluginUserEnterAndExit\server\Java\src and farther down several more folders. If you were to write your own plug-in, the Java source code might resemble PluginUserEnterAndExit.java, but it could be much more complicated as well.

Deploying the compiled plug-in

Navigate to \examples\PluginUserEnterAndExit\server\Java\dist\. Notice the PluginUserEnterAndExit folder here. If you wish to use the PluginUserEnterAndExit plug-in as it is, this folder needs to be copied to your ElectroServer 4 folder, in the \server\extensions\ subfolder. Just drop the full PluginUserEnterAndExit folder from dist into the extensions folder.

Look at the contents of this folder, either before or after you copy it. extension.xml contains the required XML tags so that ES4 can use the plug-in. The classes folder contains the compiled Java class file for PluginUserEnterAndExit.java.

The next time the ES4 server is rebooted, this plug-in will be available.

Server-level plugins require an additional step. See Server-level Plugin for details.

Verify deployment

Shutdown the ES4 server, then start it again. Since you are likely in or near the ElectroServer 4 folder, you can simply double-click on the Electro-Server.com icon.

Open the ElectroServer Web Administrator, which is likely found at https://localhost:8080/admin/ . Click the Extensions tab. You should now see "Extension [PluginUserEnterAndExit] (0)" listed. It is ready to use!

Test the plug-in

Navigate to \examples\PluginUserEnterAndExit\client\ActionScript2\dist\ . This folder contains a compiled client application to test PluginUserEnterAndExit. Run Example.swf and "Join Room" and "Leave Room". Check the server console after each button click. You should see

  User entering...
  User exiting...

Customizing "Pig Latin" Plug-in

Let's create a slightly more complicated plug-in, that will translate all public messages in a room. We will translate all messages into Pig Latin, but you could easily modify the code to do other translations such as:

  • Replace common Internet shorthand with Standard English, such as expanding "brb" to "be right back".
  • Replace profanity with a non-offensive alternative, either other words or a random collection of !@#$%^&*.
  • Change each letter to a different letter using some room-dependent cipher, for a game that involves players needing to break the cipher.

Create the Java code

We can choose to extend the BasePlugin class, or implement both the Plugin and RoomUserEvents interfaces. The key method to write is userSendPublicMessage. Here's one way to do that method:

   public ChainAction userSendPublicMessage(UserPublicMessageContext context) {
       String message = context.getMessage();
       PigLatinTranslator plTranslator = new PigLatinTranslator();
       String returnMessage = plTranslator.translate(message.trim());
       context.setMessage(returnMessage);
       return ChainAction.OkAndContinue;
   }

We will also need a separate PigLatinTranslator class.

Note: ElectroServer 4.03 includes PluginPigLatin as one of the examples.

Deploy the compiled plug-in

Compile your Java classes as classes, not as a JAR file. If you use NetBeans, you can simply copy the entire classes folder found in the project's build folder.

Create a PluginPigLatin folder in the ES4's \server\extensions\ folder for your plug-in. In that same PluginPigLatin folder, add a new extension.xml file. You can copy this from another example and just edit if you like. Here is what we need for PluginPigLatin's extension.xml:

  <?xml version="1.0" encoding="utf-8" ?>
  <Extension>
    <Name>PluginPigLatin</Name>
      <Plugins>
          <Plugin>
              <Handle>PluginPigLatinExample</Handle>
              <Type>Java</Type>
                 <Path>com.electrotank.electroserver4.examples.pluginpiglatin.PluginPigLatin</Path>
          </Plugin>
      </Plugins>
  </Extension>

The next time the ES4 server is rebooted, this plug-in will be available.

Verify deployment

Shutdown the ES4 server, then start it again. Since you are likely in or near the ElectroServer 4 folder, you can simply double-click on the Electro-Server.com icon.

Open the ElectroServer Web Administrator, which is likely found at https://localhost:8080/admin/ . Click the Extensions tab. You should now see "Extension [PluginPigLatin] (0)" listed. It is ready to use!

If you still have the PluginUserEnterAndExit folder inside \server\extensions, you should see two extensions listed. You may add as many extensions as you need, and each extension may have multiple plug-ins.

Create the Flash client for testing

We are just going to create a very simple flash client to send messages and also receive them.

Create a new .fla. Open the Components window and on frame 1 add a new TextInput component and label it c_messageInput. Also add a TextArea component and label it c_chatBox.

Now we are going to need to add quite a bit of code to frame 1:

First, add the following imports:

  import com.electrotank.electroserver4.ElectroServer;
  import com.electrotank.electroserver4.message.event.*;
  import com.electrotank.electroserver4.message.request.*;
  import com.electrotank.electroserver4.message.response.*;
  import com.electrotank.electroserver4.message.MessageType;
  import com.electrotank.electroserver4.room.Room;
  import com.electrotank.electroserver4.plugin.Plugin;
  import flash.display.Sprite;
  import flash.events.Event; 
  import fl.events.ComponentEvent;


Now we need to create the ElectroServer instance, setup the needed listener and then connect to the server. (So here we are listening for connecting, logging in, joining a room, and receiving a public message). We also declare a couple variable and add a listener to detect when the enter button is pressed (while the input text box is the focus).

  es = new ElectroServer();
  es.addEventListener( MessageType.ConnectionEvent, "onConnectionEvent", this );
  es.addEventListener( MessageType.LoginResponse, "onLoginResponse", this );
  es.addEventListener( MessageType.JoinRoomEvent, "onJoinRoomEvent", this );
  es.addEventListener( MessageType.PublicMessageEvent, "onPublicMessageEvent", this );
  es.createConnection( "127.0.0.1", 9898 );
  
  c_messageInput.addEventListener( ComponentEvent.ENTER, sendPublicMessage );
  
  var isSend:Boolean = false;
  var myRoom:Room;

Next we define the onConnectionEvent function. It checks to see if connection was successful, and then creates a random username and sends a LoginRequest to the server.

  function onConnectionEvent( e:ConnectionEvent )
  {
  	if( e.getAccepted() )
  	{
  		output( "Connected!" );
  		
  		var login:LoginRequest = new LoginRequest();
  		var randNum = Math.round( Math.random()*10000 );
  		login.setUserName( "user" + randNum );
  		
  		es.send( login );
  		
  	}
  	else
  	{
  		output( "Connection Failed" );
  	}
  }

Next, the onLoginResponse function checks to see if the login was successful and if it was attempts to create/join a room.

Note: The CreateRoomRequest will see if the given room exists. If it does not, it is created and the user joins it. If it is, the user just joins it.

The room name and zone name are set for the CreateRoomRequest and then we add the Pig Latin plugin to the room by specifying the information found in Extension.xml.

  function onLoginResponse( e:LoginResponse )
  {
  	if( e.getAccepted() )
  	{
  		output( "Logged in!" );
  		
  		var roomRequest:CreateRoomRequest = new CreateRoomRequest();
  		
  		roomRequest.setZoneName( "Chat" );
  		roomRequest.setRoomName( "Lobby" );
  		
  		var plugin:Plugin = new Plugin();
  		plugin.setExtensionName( "PluginPigLatin" );
  		plugin.setPluginHandle( "PluginPigLatinExample" );
  		plugin.setPluginName( "PluginPigLatinExample" );
  		
  		roomRequest.setPlugins( [plugin] );
  		
  		es.send( roomRequest );
  		
  	}
  	else
  	{
  		output( "Log in failed. ");
  	}
  	
  }

When a room has successfully been joined, we receive a JoinRoomEvent and the onJoinRoomEvent function is called. This function just sets the value of the current room and then sets isSend to true.

  function onJoinRoomEvent( e:JoinRoomEvent )
  {
  	myRoom = e.room;
  	isSend = true;
  	
  }

The sendPublicMessage function retrieves the text from the message input, and makes sure it is not blank and isSend is true. Then it sends a PublicMessageRequest to the server containing the room information and the message.

  function sendPublicMessage( event:Event )
  {
  	var msg:String = c_messageInput.text;
  	if (msg != "" && isSend) {
  		//Empty the textbox
  		c_messageInput.text = "";
  		//create the request
  		var pmr:PublicMessageRequest =new PublicMessageRequest();
  		pmr.setRoomId(myRoom.getRoomId());
  		pmr.setZoneId(myRoom.getZone().getZoneId());
  		pmr.setMessage(msg);
  		//send it
  		es.send(pmr);
  	}
  }

The onPublicMessageEvent function is called when a public message is received. It extracts the information from the PublicMessageEvent and outputs it.

  function onPublicMessageEvent( e:PublicMessageEvent )
  {
  	output( e.getUserName()+": " + e.getMessage() );
  }

The output function simply appends the message to the TextArea's text.

  function output( toOutput )
  {
  	c_chatBox.appendText( toOutput +"\n" );	
  }

And that's it, we are finished the client.

Test the plug-in

Now to test this, run ElectroServer and once it is on, run the client. You should see messages that connection and login are successful. Then, when you type a message in and press enter to send it, it should return in Pig Latin.

Finished

And that's it! You've finished the client and server parts.

Personal tools
download