import java.lang.String;
import java.net.*;
import java.io.*;
import Message;

public class MsgSocket
{
   private Socket con;
   public MsgSocket( String address, int p ) throws IOException
   {
      con = new Socket( address, p );
   }
   public void write( Message m ) throws IOException
   {
      byte [] msg = m.getBytes();
      int length = msg.length + 2;
      byte [] data = new byte[ length ];
      data[0] = (byte)(length - 2);
      data[1] = m.getType();
      for(int index = 2; index < length; index++ )
         data[index] = msg[index - 2];
      con.getOutputStream().write( data );
   }
   public Message read() throws IOException
   {
      Message temp = null;
      InputStream in = con.getInputStream();
      while(in.available() == 0);
      int length = in.read();
      byte [] dat = new byte[ length ];
      int type = in.read();
      in.read( dat );
      temp = new Message( (byte)type, dat );
      return temp;
   }
   public boolean hasData() throws IOException
   {
      return con.getInputStream().available() > 0;
   }
   public void close() throws IOException
   {
      con.close();
   }
}
