Java Reference
In-Depth Information
System.out.println(“Connecting to “ + serverName
+ “ on port “ + port);
Socket client = new Socket(serverName, port);
System.out.println(“Just connected to “
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF(“Hello from “
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println(“Server says “ + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
The following code from the GreetingServer class (available on the Web site
for this topic) is identical to the SimpleServer class discussed earlier, except
that it reads in a string from a client and sends a message back to the client. The
server then closes the socket and invokes accept() again for the next client that
comes along. Study the program carefully to see how this is accomplished:
System.out.println(“Waiting for client on port “ +
serverSocket.getLocalPort() + “...”);
Socket server = serverSocket.accept();
System.out.println(“Just connected to “
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF(“Thank you for connecting to “
+ server.getLocalSocketAddress() + “\nGoodbye!”);
server.close();
The GreetingServer and GreetingClient programs can be executed on two
different computers that are on the same network, or you can run them
both on the same computer. When the client and server are on the same
computer, the client can use localhost as the name of the server to
connect to. Note that running the two programs on the same computer
requires two command prompts.
Search WWH ::




Custom Search