/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * TimeServer.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 5-3: * Write a simple server that reports the current time (in textual form) to any * client that connects. Use Example 5-5, HttpMirror, as a framework for your * server. This server should simply output the current time and close the con- * nection, without reading anything from the client. You need to choose a port * number that your service listnes on. Use the GenericClient program of * Example 5-8 to connect to this port and test your program. To do this, * encode the appropriate port number into the URL. HttpClient sends an * extraneous GET request to the time server, but it still displays the server's * response. * * @author Matthew Feldt * @version 1.0, 03/07/2001 20:41 */ package com.feldt.examples.net; import java.io.*; import java.net.*; import java.util.*; public class TimeServer { public static void main(String args[]) { final String usage = "Usage: java TimeServer "; try { // parse command line for TimeServer port if (args.length != 1) { System.err.println(usage); System.exit(-1); } int port = Integer.parseInt(args[0]); // create TimeServer socket on specified port ServerSocket ss = new ServerSocket(port); // loop infinitely, responding to all connections for(;;) { // wait for client connections Socket client = ss.accept(); // create output stream to talk to the client PrintWriter out = new PrintWriter(client.getOutputStream()); // send current time and date out.print(new Date() + "\n"); // close the output stream and client connection out.close(); client.close(); } } catch (Exception e) { System.err.println(e); System.err.println(usage); } } }