TimeServer.java Source code

Java tutorial

Introduction

Here is the source code for TimeServer.java

Source

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();
    }

}