home *** CD-ROM | disk | FTP | other *** search
Java Source | 1996-08-14 | 1.9 KB | 71 lines |
- /*
- * @(#)Battle.java 1.00
- */
- package games.Battle.shared.comm;
-
- import java.io.*;
-
- /**
- * An abstract base class for all battle communication data packets.
- * <P>
- * Classes derived from BattlePacket encapsulate some sort of
- * object that needs to be transmitted between the server game
- * engine and the client game player, in either direction.
- * <P>
- * Derived classes implement the methods toBytes() and fromBytes()
- * to convert themselves to and from a stream of bytes. BattlePacket
- * implements the writeTo() and readFrom() methods to provide transmission
- * of the data to and from an Input/OutputStream
- *
- * @version 1.00 02/02/96
- * @author Jay Steele
- * @author Alex Nicolaou
- */
- public abstract class BattlePacket
- {
- /**
- * Converts this BattlePacket to an array of bytes for
- * transmission.
- */
- protected abstract byte[] toBytes();
-
- /**
- * Converts the given array of bytes into a particular
- * BattlePacket.
- * @param data the array of data to be converted
- */
- protected abstract void fromBytes(byte[] data);
-
- /**
- * Reads data from the given input stream and builds a
- * particular BattlePacket from that data.
- * @param is the input stream from which the data is pulled
- */
- public int readFrom(InputStream is)
- throws java.io.IOException
- {
- DataInputStream dis = new DataInputStream(is);
- short size = dis.readShort();
- byte[] buffer = new byte[size];
- dis.readFully(buffer);
- fromBytes(buffer);
- return size;
- }
-
- /**
- * Writes this BattlePacket to the given output stream
- * @param os the output stream on which to write the data
- */
- public void writeTo(OutputStream os)
- throws java.io.IOException
- {
- byte[] buf = toBytes();
- byte[] buffer = new byte[buf.length + 2];
- buffer[0] = (byte)((buf.length >>> 8) & 0xFF);
- buffer[1] = (byte)(buf.length & 0xFF);
- for (int i = 0; i < buf.length; i++)
- buffer[i+2] = buf[i];
- os.write(buffer, 0, buffer.length);
- }
- }
-