Simple client class


Class that handles a Socket in an extra Thread. The main function implements a simple client.

import java.net.Socket;
import java.net.UnknownHostException;
import java.net.ConnectException;
import java.io.*;

public class MySocket extends Thread
{
  static final String DEFAULT_SERVER = "localhost";
  static final int DEFAULT_PORT = 4433;

  Socket socket = null;
  PrintWriter output = null;
  BufferedReader input = null;

  public MySocket()
  {
    this(DEFAULT_SERVER, DEFAULT_PORT);
  }

  public MySocket(String server, int port)
  {
    try
    {
      this.socket = new Socket(server, port);
    }
    catch(ConnectException connectexception)
    {
      System.out.println(connectexception
        + " Maybe the Server is not running");
    }
    catch(UnknownHostException unknown_host_exception)
    {
      unknown_host_exception.printStackTrace();
    }
    catch(IOException ioexception)
    {
      ioexception.printStackTrace();
    }

    init_io();
  }

  public MySocket(Socket socket)
  {
    this.socket = socket;
    init_io();
  }

  /** inits some private variables. */
  private void init_io()
  {
    try
    {
      output = new PrintWriter(socket.getOutputStream());
      input = new BufferedReader(
        new InputStreamReader(
          socket.getInputStream()));
    }
    catch(IOException ioexception)
    {
      ioexception.printStackTrace();
    }

    System.out.println("Connected to: "
      + socket.getInetAddress()
      +":"+ socket.getPort());
  }


  /** Sending data.*/
  public void send(String data)
  {
    output.write(data);
    output.flush();
  }

  /** Reading a single line.*/
  public String receiveLine()
  {
    try
    {
      return input.readLine();
    }
    catch(IOException ioexception)
    {
      return null;
    }
  }

  public String receive()
  {
    return load(input);
  }


  public static String load(BufferedReader in)
  {
    StringBuffer lines = new StringBuffer();

    try
    {
      String line;

      while ((line = in.readLine())!=null)
        lines.append(line+"\n");

      in.close();
    }
    catch(IOException io_exception)
    {
      io_exception.printStackTrace();
    }

    return lines.toString();
  }


  public static void main(String args[])
  {
    try
    {
      MySocket client = new MySocket();

      client.send("Test\n");
      String result = client.receive();

      if (result!=null)
        System.out.println(result);
      else
        System.out.println("NO Result");

      client.socket.close();
    }
    catch(IOException e)
    {
      System.out.println(e);
    }
  }
}


Java Tutorial - Standard Classes Jens Trapp, 1997