Spider Monkey tutorial

AlienCat Jul 13th, 2011 382 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Simple connections
  3.         To make a connection you need a server and some clients. To ititilize and start a server on TCP port 00 and UDP port 5050 you use this code:
  5.  Server myServer = Network.createServer(00, 5050);
  6.  myServer.start();
  8.         Then you create and start the client and connect it to the server on localhost. If you have the server on another IP, simply replace localhost with that ip.
  10.  Client myClient = Network.connectToServer("localhost", 00, 5050);
  11.  myClient.start();
  13.  It is hard to know if that really works cuase nothing will really happen. But if the code runs without errors and exceptions it should work, and that is possible to check with various functions like myServer.getConnections().size(); that will return how many clients who are connected to the server.
  16. Sending and receiving messages
  18.         Afer you have created an server-client connection you might want to send data from the client to server or the oposite. That is done by messages.
  19.         The first thing to do is to create a message class containing what to send over. It could be chatmessages, position data, diffrent actions etc. Here we just store a hello message.
  21.  @Serializable
  22.  public static class HelloMessage extends AbstractMessage {
  23.          public String hello = "Hello!";
  25.          public HelloMessage()
  26.          {
  28.          }
  29.  }
  31.  For some reason the massages needs a default constructor without any argument. However that should only be needed if you haver other constructors with arguments. This message should be in it's own file, so if you choose to have it that way the static modifier should be removed.
  33.  Before we do anything we should register the message class to the Serializer. Then we add message listeners for the message and finally send the message from the client to the server:
  35.  Serializer.registerClass(HelloMessage.class);
  36.  myServer.addMessageListener(new ServerListener(), HelloMessage.class);
  37.  myClient.addMessageListener(new ClientListener(), HelloMessage.class);
  39.  Message m = new HelloMessage();
  41.  myClient.send(m);
  44.  You need to register the message class to the Serializer on both server and every client. However, this will not work without listeners, here we implement one for the client and one for the server.
  46.         public static class ClientListener implements MessageListener<Client>
  47.         {
  48.                 public void messageReceived(Client source, Message message) {
  49.                         HelloMessage helloMessage = (HelloMessage)message;
  50.                         System.out.println(helloMessage.hello);
  51.                 }
  52.         }
  54.         public static class ServerListener implements MessageListener<HostedConnection>
  55.         {
  56.                 public void messageReceived(HostedConnection source, Message message) {
  57.                     HelloMessage helloMessage = (HelloMessage)message;
  58.                         System.out.println(helloMessage.hello);
  59.                         helloMessage.hello = "Hi!";
  60.                         source.send(helloMessage);
  61.                 }
  62.         }
  64. The client listener will just print the message it gets from the server and the server listener will print the message, then change it and send it back to the client. If the program is big, you might put the listeners in own files, rememer the remove static then.
  67. Serializable annotation
  69. This quote explians what a serialization annotation is:
  71. "The Serializable annotation is used to determine which serializer you want to use for your message, and which ID you want to register to it. If you specify no ID and no serializer, a ID will be assigned, and the default serializer will be used. The problem with specifying no ID is that you have to have the same order of registration on both the client and server, otherwise serializing will go wrong."
  73. So if you have serveral message classes, you should consider to use a static function that register the messages to the Serializer that both the client and the server can use. You can also give an id to the classes you want to register to be sure that you got the same id regardless of the order you register them.
  75. @Serializable(id=3)
  78. Serialization system
  80. This quote explains how the serialization works:
  82. "SpiderMonkey's Serializer class is the entry point for everything serializing. Serializing is the act of translating an object into bytes, so it can be transferred over the network. SpiderMonkey does this by having Serializer classes (they extend Serializer itself), and having some static methods available in the Serializer class. A serializer does not exist without a class it can serialize - this means that Serializers need to be registered with a class. For example, the String type is registered to the StringSerializer class. Without the String type being registered, there'd be no instance of StringSerializer.""
  83. Writing your own serializer"
  85. You might need to serialize something yourself for some reason. That is mostly becuse you can optimize the data you want you send that way so it saves a lot of bytes. This part is about making a serializer for an InetAddress, that is the IP adress and then sending it through the custom serializer. To to that you extend the general Serializer class and implement the methods readObject(ByteBuffet, Class<T>) and writeObject(ByteBuffer, Object). Althrough reading and writing the object is easy, you will have to know how to convert the objects to bytes.  
  87. public static class InetAddressSerializer extends Serializer {
  88. @Override
  89.    public <T> T readObject(ByteBuffer data, Class<T> c) throws IOException {
  90.            byte[] address = new byte[];
  91.            data.get(address);
  92.            return (T)InetAddress.getByAddress(address);
  93.    }
  95.         @Override
  96.         public void writeObject(ByteBuffer buffer, Object object) throws IOException {
  97.                 InetAddress address = (InetAddress)object;
  98.                 buffer.put(address.getAddress());
  99.         }
  100. }
  103. Then you register the Serializer with the InetAddress class.
  105. Serializer.registerClass(InetAddress.class, new InetAddressSerializer());
  108. Next step is to make an message that use the serializer.
  110. @Serializable
  111. public static class AddressMessage extends AbstractMessage {
  112.         public InetAddress addr;
  113.         public AddressMessage(InetAddress addr) { this.addr = addr; }
  114.                       public AddressMessage() { }
  116. }
  118. After that you are able to send the message.
  120. InetAddressSerializer.registerClass(AddressMessage.class);
  121. myServer.addMessageListener(new SrvrHandler(), AddressMessage.class);
  122. Message am = new AddressMessage(InetAddress.getByName(""));
  123. myClient.send(am);
  125. If you still use HelloMessage you can change the code in messageReceived to
  127. if(message instanceof AddressMessage)
  128. {
  129.         AddressMessage m = (AddressMessage)message;
  130.         System.out.println(m.addr.toString());
  131. }
  133. if(message instanceof HelloMessage)
  134. {
  135.         HelloMessage helloMessage = (HelloMessage)message;
  136.         System.out.println(helloMessage.hello);
  137.         helloMessage.hello = "Hi!";
  138. }
  141. The output will be the ip to
RAW Paste Data
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!