Create Time Server to serve time value - Java Network

Java examples for Network:ServerSocket

Description

Create Time Server to serve time value

Demo Code

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 Main extends Thread {
  private ServerSocket sock;

  public Main() {
    super();/*from   w w w . j  a  v a2s .  c o m*/
    try {
      sock = new ServerSocket(4415);
      System.out.println("TimeServer running ...");
    } catch (IOException e) {
      System.out.println("Error: couldn't create socket.");
      System.exit(1);
    }
  }

  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);
        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) {
    Main server = new Main();
    server.start();
  }

}

Result


Related Tutorials