Java Reference
In-Depth Information
Display 19.7
Date and Time Server (part 2 of 2)
Sample Dialogue
Output when the client program in Display 19.8 connects to the server program.
Waiting for a connection on port 7654.
Connection made, waiting for client to send their name.
Sent: Welcome, Dusty Rhodes, Today is Sun Nov 20 12:18:21 AKDT 2011
Display 19.8
Date and Time Client (part 1 of 2)
1 import java.net.Socket;
2 import java.io.DataOutputStream;
3 import java.io.BufferedReader;
4 import java.io.InputStreamReader;
5 import java.io.IOException;
6 public class DateClient
7 {
8 public static void main(String[] args)
9 {
10 try
11 {
12 String hostname = "localhost";
13 int port = 7654;
localhost refers to the same, or local,
machine that the client is running on.
Change this string to the appropriate
hostname (e.g., my.server.com) if the
server is running on a remote machine.
14 System.out.println("Connecting to server on port " + port);
15 Socket connectionSock = new Socket(hostname, port);
16 BufferedReader serverInput = new BufferedReader(
17 new InputStreamReader(connectionSock.getInputStream()));
18 DataOutputStream serverOutput = new DataOutputStream(
19 connectionSock.getOutputStream());
20 System.out.println("Connection made, sending name.");
21 serverOutput.writeBytes("Dusty Rhodes\n");
22 System.out.println("Waiting for reply.");
23 String serverData = serverInput.readLine();
24 System.out.println("Received: " + serverData);
25 serverOutput.close();
26 serverInput.close();
27 connectionSock.close();
28 }
(continued)
 
 
Search WWH ::




Custom Search