Thread based ServerSocket : ServerSocket « Network « Java Tutorial






import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainClass {
  public static void main(String[] args) throws IOException {
    int port = 9000;

    ServerSocket server = new ServerSocket(port);
    while (true) {
      Socket socket = server.accept();
      Thread stuffer = new StuffThread(socket);
      stuffer.start();
    }

  }

}

class StuffThread extends Thread {
  private byte[] data = new byte[255];

  private Socket socket;

  public StuffThread(Socket socket) {

    for (int i = 0; i < data.length; i++)
      data[i] = (byte) i;
    this.socket = socket;
  }

  public void run() {
    try {
      OutputStream out = new BufferedOutputStream(socket.getOutputStream());
      while (!socket.isClosed()) {
        out.write(data);
      }
      socket.close();
    } catch (Exception e) {
    }
  }
}








19.14.ServerSocket
19.14.1.Create a ServerSocket
19.14.2.Hello Server
19.14.3.Time server
19.14.4.Thread based ServerSocket
19.14.5.Generic Server
19.14.6.Timer server with Thread
19.14.7.A multithreaded Socket Server
19.14.8.Get IP address from NetworkInterface and create server socket
19.14.9.Logging Server based on SocketServer
19.14.10.Data server
19.14.11.Object server
19.14.12.Compressed socket
19.14.13.Zip server socket