/*
The code is available only to persons
currently affiliated with any of the following,
      o Universities and schools
      o Non-commercial research organizations
      o Registered not-for-profit organizations
      o Registered charities
For these people, the license is of the form of
the GNU Public License version 2.  The restrictions
must remain attached to this and any subsequently derived code.
All other people have no implicit right to use, read, or copy
this software unless granted by Mr. Deck
THIS SOFTWARE IS PROVIDED "AS IS" AND MR. DECK
MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, HE
MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT-
ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE
OF THE LICENSED SOFTWARE AND DOCUMENTATION WILL NOT
INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR
*/

import java.awt.*;
import java.io.*;
import java.net.*;


public class connection
{
   boolean              error=true;
   Socket               s;
   BufferedOutputStream out;
   DataInputStream      in;

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

   byte[] receive() throws IOException {
	if(in!=null){
	 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;
	}else return null;
   }                

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