Site hosted by Angelfire.com: Build your free website today!
 

Client Side Socket

Using Socket is pretty simple, first creates a new instance passing it the host name and the port number. Then create the concret stream classes for the input and the output stream.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.net.Socket;

/**
 * @author jack
 */
public class SocketClient {
  static String host = "www.hsi.com.hk";
  static int port = 80;
  static String path = "/constituent/content.html";
  public static void main(String args[]) {j
    BufferedReader din = null;
    BufferedWriter dout = null;
    try {
      Socket socket = new Socket(host, port);
      din = new BufferedReader(
        new InputStreamReader(socket.getInputStream()));
      dout = new BufferedWriter(
        new OutputStreamWriter(socket.getOutputStream()));
      dout.write("GET " + path + " HTTP/1.0\n\n");
      dout.flush();
    } catch (IOException e) {
      e.printStackTrace();
      System.exit(0);
    }
    while (true) {
      String s;
      try {
        s = din.readLine();
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
      if (s == null)
        break;
      System.out.println(s);
    }
  }
}