home *** CD-ROM | disk | FTP | other *** search
/ The Net: Ultimate Internet Guide / WWLCD1.ISO / pc / java / enxle1f6 / src / games / battle / shared / comm / battlepacket.java next >
Encoding:
Java Source  |  1996-08-14  |  1.9 KB  |  71 lines

  1. /*
  2.  * @(#)Battle.java 1.00
  3.  */
  4. package games.Battle.shared.comm;
  5.  
  6. import java.io.*;
  7.  
  8. /**
  9.  * An abstract base class for all battle communication data packets.
  10.  * <P>
  11.  * Classes derived from BattlePacket encapsulate some sort of
  12.  * object that needs to be transmitted between the server game
  13.  * engine and the client game player, in either direction.
  14.  * <P>
  15.  * Derived classes implement the methods toBytes() and fromBytes()
  16.  * to convert themselves to and from a stream of bytes. BattlePacket
  17.  * implements the writeTo() and readFrom() methods to provide transmission
  18.  * of the data to and from an Input/OutputStream
  19.  *
  20.  * @version 1.00 02/02/96
  21.  * @author Jay Steele
  22.  * @author Alex Nicolaou
  23.  */
  24. public abstract class BattlePacket
  25. {
  26.     /**
  27.      * Converts this BattlePacket to an array of bytes for
  28.      * transmission.
  29.      */
  30.     protected abstract byte[] toBytes();
  31.  
  32.     /**
  33.      * Converts the given array of bytes into a particular
  34.      * BattlePacket.
  35.      * @param data the array of data to be converted
  36.      */
  37.     protected abstract void fromBytes(byte[] data);
  38.  
  39.     /**
  40.      * Reads data from the given input stream and builds a 
  41.      * particular BattlePacket from that data.
  42.      * @param is the input stream from which the data is pulled
  43.      */
  44.     public int readFrom(InputStream is) 
  45.         throws java.io.IOException
  46.     {
  47.         DataInputStream dis = new DataInputStream(is);
  48.         short size = dis.readShort();
  49.         byte[] buffer = new byte[size];
  50.         dis.readFully(buffer);
  51.         fromBytes(buffer);
  52.         return size;
  53.     }
  54.  
  55.     /**
  56.      * Writes this BattlePacket to the given output stream
  57.      * @param os the output stream on which to write the data
  58.      */
  59.     public void writeTo(OutputStream os) 
  60.         throws java.io.IOException
  61.     {
  62.         byte[] buf = toBytes();
  63.         byte[] buffer = new byte[buf.length + 2];
  64.         buffer[0] = (byte)((buf.length >>> 8) & 0xFF);
  65.         buffer[1] = (byte)(buf.length & 0xFF);
  66.         for (int i = 0; i < buf.length; i++)
  67.             buffer[i+2] = buf[i];
  68.         os.write(buffer, 0, buffer.length);
  69.     }
  70. }
  71.