Time server

In this chapter you will learn:

  1. Timer server with Thread

Timer server with Thread

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
/*  ja v  a  2  s  .com*/
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();
  }

}

The code above is a thread based time server. When a client connects to the time server it echoes back the current time.

Next chapter...

What you will learn in the next chapter:

  1. Zip server socket
Home » Java Tutorial » Socket

Socket

    Socket
    Socket creation
    Socket read
    HTTP client
    SMTP Client
    Cipher Socket
    Socket connection and thread

ServerSocket

    ServerSocket
    ServerSocket connection
    File server and client
    Thread based Server
    Time server
    SocketServer based zip server
    ServerSocketChannel
    Channel selector

SocketChannel

    SocketChannel Creation
    Read and write with SocketChannel
    SocketChannel based HTTP client
    SocketChannel Asynchronous

ServerSocketChannel

    ServerSocketChannel
    Channel selector

SSL

    SSL Client Socket
    SSL Server Socket

UDP

    DatagramSocket
    DatagramChannel
    Multicast Group

Cookie

    Cookies