Java Reference
In-Depth Information
try ( // Create a socket connecting to server
Socket clientSocket = new Socket("localhost", 9000);
// Set up input stream reader to read keyboard input
BufferedReader keyboardReader =
new BufferedReader(new InputStreamReader(System.in, "UTF-8"));
// Set up input stream reader (from server)
DataInputStream incoming =
new DataInputStream(clientSocket.getInputStream());
// Set up output stream writer (to server)
DataOutputStream outgoing = new
DataOutputStream(clientSocket.getOutputStream());
) {
// Read message from user
System.out.println("Enter message to send to server: ");
String message = keyboardReader.readLine();
// Send message to server
outgoing.writeUTF(message + '\n');
// Read the reply from server
System.out.println("Server replied: ");
try {
String reply = incoming.readUTF();
System.out.print(reply);
} catch (EOFException eof) {
// Do nothing... server has closed the connection
}
// Close the connection
clientSocket.close();
System.out.println("Connection closed gracefully");
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.
To try out this code, start TCPServer first, followed by TCPClient . Note that you might get
a warning from your firewall telling you that network activity is being requested by Java.
Naturally, to make the code work, you should allow this. You should be able to type a message
in the TCPClient console window and receive a reply. The output for TCPServer will then read
like so:
Waiting for connection...
Waiting for message...
CLIENT SAID: Hello there server!
Waiting for connection...
Whereas for the client, you will see:
Enter message to send to server:
Hello there server!
Server replied:
MESSAGE RECEIVED
Connection closed gracefully
Search WWH ::




Custom Search