Time server
In this chapter you will learn:
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:
Home » Java Tutorial » Socket