/* Copyright Andy C. Deck 1999 All rights reserved. */    
import java.awt.*;
import java.io.*;
import java.net.*;


public class connection
{
   boolean          error=true;
   Socket           s;
   BufferedOutputStream out;
   DataInputStream  in;
   label usrLab;
   Item d = new Item();

   connection(String host, int port,label lab)
   {
       this.usrLab = lab;
       try
       {
	    s   = new Socket(host, port);
	    out = new BufferedOutputStream(s.getOutputStream());
	    in  = new DataInputStream(new BufferedInputStream(s.getInputStream()));
       }
       catch (Exception e)
       {
	    usrLab.setText(Env.serverdown);
	    error = true;
		return;
       }
	  error = false;
   }
	
   void sendStroke(byte buf[], int len){
     if(error) return;
      try{
	  out.write(buf,0,len);
	  out.flush();
       	}catch( IOException e){
	       error = true;
	       e.printStackTrace();
       }	
   }

   void sendString(String s){
     int n = s.length();
     int cnt = n+2;
     if(n>0){
	byte[] buf = new byte[n+4];
	buf[0] = (byte)(((int)cnt>>8)&0x00ff);
        buf[1] = (byte)(cnt&0x00ff);     
	buf[2] = Env.TEXT;
	buf[3] = 0;
	s.getBytes(0,n,buf,4);
        try{
	  out.write(buf);
	  out.flush();
       	}catch( IOException e){
	       error = true;
	       e.printStackTrace();
        }	
     }
   }

	
   void sendCmd(byte b){
      byte cmd[] = { 0,1,b };
       try{
		 out.write(cmd);
		  out.flush();
        }catch( IOException e){
		       error = true;
		       e.printStackTrace();
	}
	return;
    }

    byte[] receive() throws IOException
    {
	int n=0;
	byte[] head = new byte[2];
 	in.readFully(head);
	n = ((head[0]<<8)&0xff00)|(head[1]&0x00ff);
	if(n==0) return null;
	byte[] buf = new byte[n];
	in.readFully(buf,0,n);
	return buf;
    }                

    void close()
    {
	  try { 
		if(out!=null)	out.close();
		if( s  !=null ) s.close();
        	s   = null;
		out = null;
		in  = null;
	  }
	  catch (IOException e) { 
		error = true;
	  }
    }

}
