Hello World Plugin Tutorial

From EsWiki

Jump to: navigation, search

This tutorial covers the creation of your first plugin.

Contents

What You'll Learn

  • How to put a plugin on the server and have it communicate with the client

Prerequisites

Download

If you wish to simply download the entire set of Hello World Plugin files (both server and client, source code and compiled), it is found in HelloWorldPluginsTutorial.zip.

Let's Get Started!

The following steps will show you how to make your first plugin.

Overview

A plugin is a set of code that is run on the server, can communicate with clients and is normally created when a room is created (unless it is a server level plugin).

What we want this plugin to do is accept two numbers from the player, multiply them together and return the result.

So what we need to figure out for this plugin (or any plugin we want to make) is what messages are being sent from the client to the server, and what messages from the server to the client.

From the client to the server we are going to need to send:

  • The two numbers that will be multiplied together

In this example there is only one message going from the client to the server, but it many examples, there will be a variety of messages.

From the server to the client we are going to need to send:

  • The result of multiplying the two numbers together

Likewise, there can be more than one type of message, but there is only one in this situation.

We will need to code the server code from scratch and modify the Simple Chat client.

We'll look at the server side part first. This tutorial covers the server-side plugin creation in both Java and Actionscript, so you may choose which one to do.

Server side (Java)

New Java project

Create a new project and add a package to it called helloworldplugin, with a file called Main.java as your Main class.

If you are using NetBeans, go to File -> New Project -> Java -> Java Application. Hit next. Place the project where you want, and call it HelloWorldPlugin. Hit Finish.

We also need to add ElectroServer4.jar as a library the project accesses. In NetBeans, under the Projects panel (defaults in the top left of the screen), open the HelloWorldPlugin project. Then right click on libraries and select add JAR/folder. Find where you installed ElectroServer (likely in Program Files), then go into server/lib and select ElectroServer4.jar .

Now we are ready to create the plugin class.

Extend BasePlugin

Add a package to your project, which can be called helloworldplugin or com.mycompany.mypackage or whatever you like.

Add a class to the package you just created, which can be called Main or HelloWorldPlugin or whatever you like.

Lets add all the imports we are going to need for this class.

Copy and paste this after the line package helloworldplugin; .

import com.electrotank.electroserver4.extensions.ChainAction;
import com.electrotank.electroserver4.extensions.api.value.UserPublicMessageContext;
import com.electrotank.electroserver4.extensions.BasePlugin;

Since this class will be used as a plugin, it should extend BasePlugin, so add extends BasePlugin after public class HelloWorldPlugin.

In this example, the plugin will not need to keep track of any variables, only handle what is given and then return the value.

We are not going to send a custom message to the plugin from the client (eg the coordinates of player's ship), but instead just listen in on the chat messages the player sends.

Intercepting the Message

When we override the userSendPublicMessage function, we gain access to a chain of events that occur when a message is sent from the client to the server. So we can decide in that function to alter the message, stop the message, or allow it to continue.

   	 @Override
   	 public ChainAction userSendPublicMessage(UserPublicMessageContext context) {
   		//  get the message to be translated
   		String message = context.getMessage();
 
   		if( message.startsWith("/"))
   		{
   			String [] resultsArray = message.split(" ", 3);
 
   			if( resultsArray[0].equals("/multiply") )
   			{
                           //Messages take the form:
                           // "/multiply x y"
 
                           String xString = resultsArray[1]; 
                           String yString = resultsArray[2]; 
 
                           //Take the second "word" in the array, that is the first number to be multiplied
                           int x = Integer.parseInt(xString);
                           //Take the third "word" in the array, that is the second number to be multiplied
                           int y = Integer.parseInt(yString);
                           int result = x*y;
 
                           String outputMessage = "asked what is " +xString+ "*" +yString + " equal to. The answer is: " + result;
 
                           context.setMessage( outputMessage );
   			}
   		}
 
   		//  message is not stopped by the server, allow it to continue, even though it has been changed
   		return ChainAction.OkAndContinue;
   	}

In this function, the message is first retrieved from the data that is passed in. Then if it begins with "/", we split up the string into 3 "words" using a space as the divider. If the first "word" is /multiply, we assume that the 2nd and 3rd sections are numbers and then convert them to numbers. (If they are not, errors will occur). Then we multiply the numbers, and form a string that outlines what the question was and what the answer is. Then we set this new message as the message the should be sent to all the users and return ChainAction.OkAndContinue to allow the chain of events to continue.

Now all the code is finished for the server side portion.

Deploy the Extension

To add this plugin as an extension (which is necessary), go to installation folder/server/extensions. Create a new folder called HelloWorldPlugin. Insided this folder, create a new file named extension.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Extension>
    <Name>HelloWorldExtension</Name>
    <Plugins>
          <Plugin>
               <Handle>HelloWorldPlugin</Handle>
               <Type>Java</Type>
               <Path>helloworldplugin.HelloWorldPlugin</Path>
          </Plugin>
    </Plugins>
</Extension>

If you named your class something other than HelloWorldPlugin, or your package something other than helloworldplugin, you will need to edit the Path line.

Build the Java source code and place the classes folder in the HelloWorldPlugin folder (classes folder will be found under the build folder of where your Java project is). So the file structure would look like:

  • installation folder/server/extensions/HelloWorldPlugin/extension.xml
  • installation folder/server/extensions/HelloWorldPlugin/classes/helloworldplugin/HelloWorldPlugin.class

For more information see Extension Structure and Deployment.

Restart the server for this extension to be deployed. Do this can be done via the ElectroServer administration console.

Now we will look at the client side.

Server side (Actionscript)

ActionScript File

Create a new actionscript file and call it helloworldplugin.as. We don't need to include any imports, as they are added for us by the script interpreter.

What we need to do is define the userSendPublicMessage function for the plugin, so we can edit what happens when the server receives a PublicMessageRequest. This allows to us do things like edit or stop the message, but in this case we will only edit the message.

The userSendPublicMessage function is given an UserPublicMessageContext instance as a parameter, so the first thing we do is retrieve the message from it. Then we check to see if it starts with "/" and if it does, we split it up into 3 sections based on where the spaces are. If the first "word" is "/multiply" we know the user has asked for two numbers to be multiplied. We then retrieve the two numbers to multiply, multiply them and then change the message to the one that displays the result. Finally we return ChainAction.OkAndContinue to tell the server to allow the message to be sent.

Note: The function calls seen here are to the Java API, ES4 related or not. The startsWith function is a Java String function, but is used directly in the Actionscript code. The getMessage function is part of the Electroserver Java API, but is also used in the Actionscript code.

   function userSendPublicMessage(context) {
   		//  get the message to be translated
   		var message = context.getMessage();
 
   		if( message.startsWith("/"))
   		{
   			var resultsArray = message.split(" ", 3);
 
   			if( resultsArray[0].equals("/multiply") )
   			{
   				//Messages take the form:
   				// "/multiply x y"
 
   				var x = resultsArray[1]; 
   				var y = resultsArray[2]; 
 
   				var result = x*y;
 
   				var outputMessage = "asked what is " +x+ "*" +y + " equal to. The answer is: " + result;
   				context.setMessage( outputMessage );
   			}
   		}
 
   		//  message is not stopped by the server, allow it to continue, even thought it has been changed
   		return ChainAction.OkAndContinue;
   }

Next we will look at deploying this plugin.

Deploy the Extension

To add this plugin as an extension (which is necessary), go to installation folder/server/extensions. Create a new folder called HelloWorldPlugin. Create a new file named extension.xml:

   <?xml version="1.0" encoding="utf-8" ?>
   <Extension>
   	<Name>HelloWorldExtension</Name>
   	<Plugins>
   		<Plugin>
   			<Handle>HelloWorldPlugin</Handle>
   			<Type>ActionScript</Type>
   			<Path>helloworldplugin.as</Path>
   		</Plugin>
   	</Plugins>
   </Extension>

The Path value is the name of the Actionscript file to include so if you named it differently, change that name also. Place the extension.xml file in the HelloWorldPlugin folder and also create a new folder called scripts. Inside of that folder, place the helloworldplugin.as file.

For more information see Extension Structure and Deployment.

Now we will look at the client side.

Client side (Flash)

We are going to be using Simple Chat as a base, so open up Main.as for it.

The only thing we need to add to this to link the room we create to the plugin we just made. The plugin in this example only edits public messages that are sent to the server and has no direct communication with the users.

First, add this import:

   	import com.electrotank.electroserver4.plugin.Plugin;

The only thing we need to do is actually have the plugin in the room we join. So when sending the CreateRoomRequest we need specify that this plugin should be added to the room.

A new instance of Plugin is made, and then the extension name, plugin handle and plugin name are sent. Then the setPlugins command on the CreateRoomRequest object adds the plugin.

Note: The information given for the extension and plugin handle come from the Extensions.xml file

   	private function joinRoom():void 
   	{
   		//tries to create a room. if it already exists, then you join that room
   		//create the request
   		var crr:CreateRoomRequest = new CreateRoomRequest();
   		crr.setRoomName("MyRoom");
   		crr.setZoneName("ZoneName");
 
   		//Use the settings in the Extension.xml plugin here
   		var multiplyPlugin:Plugin = new Plugin();
 
   		//Use the extension from the xml file
   		multiplyPlugin.setExtensionName( "HelloWorldExtension" );
 
   		//Use the handle from the xml file
   		multiplyPlugin.setPluginHandle( "HelloWorldPlugin" );
 
   		//This can be any name you wish to give it, but normally if there is only one
   		//of a given plugin in an extension, best to use the handle name
   		multiplyPlugin.setPluginName( "HelloWorldPlugin" );
 
   		//Finally, attach this plugin to the CreateRoomRequest (you could have more than one, only one here though)
   		crr.setPlugins( [multiplyPlugin] );
 
   		//send it
   		es.send(crr);
   	}

And that is it, you should be able to send a message of the form "/multiply 61 54" and see a result.

If you created both the Java and the Actionscript plugin, you should be able to swap them and have the client still work.

Differences Between the Java and Actionscript server code

There are a few key differences between the Java and Actionscript server side code:

  • Actionscript does not define types, Java does
  • Actionscript does not need imports for ElectroServer code, Java does
  • Actionscript is less "formal" but performs worse because it is interpreted

Note that while using Actionscript for plugins a lot of Java functions are still used but a lot of the strictness of Java is not needed. For instance, the startsWith function is in Java, not in Actionscript, but it still fluidly used in the Actionscript plugin.

Also, as an aside, to use Java functions that are not ES4 related, the whole package name must be written out (as it is not imported ).

   //The following will cause an error
   System.out.println("Test");
 
   //The following works because the package is also given
   java.lang.System.out.println("Test");

For information about importing, see this.

Finished!

Well done! You are now finished your first plugin! This is an important step in learning how to use ElectroServer. For more plugin tutorials see:

Personal tools
download