package Client;

import java.io.*;
import java.util.*;
import java.net.*;
/*
* >--TCP--<
* Author: Someone
*/
public class TCP implements Runnable{
  private Socket $sock = null;
  private InputStream $in = null;
  private OutputStream $out = null;


public TCP(String $server, int $port)throws Exception{
  $sock = new Socket($server, $port);
  $in = $sock.getInputStream();
  $out = $sock.getOutputStream();
  new Thread(this).start();
}

public void run(){
  try{
    while($sock != null){
      receive();
    }
  }catch(Exception $e){$e.printStackTrace();}
}

public void send(String $msg){
  try{
    byte[] $len = Helper.int2ba($msg.length());
    $out.write($len);
    $out.flush();
    $out.write($msg.getBytes());
    $out.flush();
  }catch(Exception $e){$e.printStackTrace();}
}

public void receive()throws Exception{
  int $len = Helper.ba2int(Helper.readBA($in, 4));
  String $msg = new String(Helper.readBA($in, $len));
  System.out.println($msg);
}

public void shutdown(){
  try{
    send("CLIENT shutting down...");
    $out.close();
    $in.close();
    $sock.close();
    $sock = null;
  }catch(Exception $e){$e.printStackTrace();}
}

}