Java Reference
In-Depth Information
LISTING 17.3
Continued
11: sock = new ServerSocket(4415);
12: System.out.println(“TimeServer running ...”);
13: } catch (IOException e) {
14: System.out.println(“Error: couldn't create socket.”);
15: System.exit(1);
16: }
17: }
18:
19: public void run() {
20: Socket client = null;
21:
22: while (true) {
23: if (sock == null)
24: return;
25: try {
26: client = sock.accept();
27: BufferedOutputStream bos = new BufferedOutputStream(
28: client.getOutputStream());
29: PrintWriter os = new PrintWriter(bos, false);
30: String outLine;
31:
32: Date now = new Date();
33: os.println(now);
34: os.flush();
35:
36: os.close();
37: client.close();
38: } catch (IOException e) {
39: System.out.println(“Error: couldn't connect to client.”);
40: System.exit(1);
41: }
42: }
43: }
44:
45: public static void main(String[] arguments) {
46: TimeServer server = new TimeServer();
47: server.start();
48: }
49:
50: }
17
The
TimeServer
application creates a server socket on port 4415. When a client con-
nects, a
PrintWriter
object is constructed from buffered output stream so that a string
can be sent to the client—the current time.
After the string has been sent, the
flush()
and
close()
methods of the writer end the
data exchange and close the socket to await new connections.