Timer server with Thread : ServerSocket « Network « Java Tutorial






import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class TimeServer extends Thread {
  private ServerSocket sock;

  public TimeServer() throws Exception {
    sock = new ServerSocket(55555);
  }

  public void run() {
    Socket client = null;

    while (true) {
      if (sock == null)
        return;
      try {
        client = sock.accept();
        BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
        PrintWriter os = new PrintWriter(bos, false);
        String outLine;

        Date now = new Date();
        os.println(now);
        os.flush();

        os.close();
        client.close();
      } catch (IOException e) {
        System.out.println("Error: couldn't connect to client.");
        System.exit(1);
      }
    }
  }

  public static void main(String[] arguments) throws Exception {
    TimeServer server = new TimeServer();
    server.start();
  }

}








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