Java Reference
In-Depth Information
After creating the socket and obtaining the socket's output stream and input stream,
the client can write to the PrintWriter in order to send data to the server. Similarly,
to receive a response from the server, the client reads from the BufferedReader
object. The testConnection() method is used to simulate a conversation between
the client and the server program using the newly created socket. To do this, the
socket , in , and out variables are checked to ensure that they are not equal to
null . If they are not equal to null , the client attempts to send a message to the serv-
er by sending a message to the output stream using out.println("Here is a
test.") . A loop is then created to listen for a response from the server by calling the
in.readLine() method until nothing else is received. It then prints the messages
that are received.
if (socket != null && in != null && out != null) {
System.out.println("Successfully connected, now
testing...");
try {
// Send data to server
out.println("Here is a test.");
// Receive data from server
while((serverResponse = in.readLine()) != null)
System.out.println(serverResponse);
} catch (IOException e) {
System.out.println(e);
System.exit(1);
}
}
The java.net.Socket class is true to the nature of the Java programming lan-
guage. It enables developers to code against a platform-independent API in order to
communicate with network protocols that are specific to different platforms. It ab-
stracts the details of each platform from the developer and provides a straightforward
and consistent implementation for enabling client/server communications.
Search WWH ::




Custom Search