Note: The example code provided here is based on a similar application in Computer Networks: A Top-Down Approach, 5th ed., by Kurose and Ross.
This tutorial provides a simple introduction to network socket programming in Java. The client will connect to a listening server on the specified host and port number, wait for the user to enter a line of text, send it to the server, and then print the response. If you followed the steps in the Echo Server Tutorial, then the output will be the same line of ASCII text converted to uppercase characters.
package edu.rutgers.sakai.java.net; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException; /** * <ol> * <li>Connects to a {@code TCPServer} on a host/port using TCP. * <li>Reads a line from standard input.</li> * <li>Sends the line to the {@code TCPServer}.</li> * <li>Reads the response and prints to standard out.</li> * <li>Disconnects from the server.</li> * </ol> * * <p> * The source code contained in this file is based on the "TCPClient" example * program provided by Kurose and Ross in <i>Computer Networking: A Top-Down * Approach</i>, Fifth Edition. * </p> * * @author Robert S. Moore * */ public class TCPClient { /** * Parses 2 parameters (server host, server port), and connects to the * server. Waits for the user to type a line of text into standard input and * transmits it to the server. Waits for a response from the server and * prints out the message. Exits after the response has been read. * * @param args <server hostname> <server port> */ public static void main(String[] args) { // Make sure both arguments are present if (args.length < 2) { TCPClient.printUsage(); System.exit(1); } // Try to parse the port number int port = -1; try { port = Integer.parseInt(args[1]); } catch (NumberFormatException nfe) { System.err.println("Invalid server port value: "" + args[1] + ""."); TCPClient.printUsage(); System.exit(1); } // Make sure the port number is valid for TCP. if (port <= 0 || port >= 65536) { System.err.println("Port value must be in (0, 65535]."); System.exit(1); } // Create the socket, returning null if an exception occurs. Socket clientSocket = TCPClient.createSocket(args[0], port); if (clientSocket == null) { System.err.println("Unable to create socket to "" + args[0] + ":" + port + ""."); System.exit(1); } // Create the input/output streams, read user input and server response. try { DataOutputStream serverOut = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader serverIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please type a line of text and press <Enter>:"); // Read the user's line String line = userInput.readLine() + "n"; // Write the line as a sequence of ASCII-encoded bytes serverOut.write(line.getBytes("ASCII")); // Always flush output streams after a message has been sent serverOut.flush(); // Read the response line from the server String response = serverIn.readLine(); System.out.println("RESPONSE: " + response); // Be sure to close all streams serverOut.close(); serverIn.close(); userInput.close(); // Closing the socket will close its input/output streams, but not others that were created. clientSocket.close(); } catch (IOException e) { System.err.println("A general exception occurred while communicating with the server: " + e.getMessage()); e.printStackTrace(); System.exit(1); } } /** * Creates a TCP socket to the provided host and port. Returns {@code null} if any exceptions are thrown or * the socket cannot be created. * @param hostname the hostname or IP address (in dotted-decimal) format for the remote {@code TCPServer}. * @param port the port number that the server is listening on. * @return a new {@code Socket} if the connection is made successfully, else {@code null}. */ private static Socket createSocket(final String hostname, final int port) { try { Socket clientSocket = new Socket(hostname, port); return clientSocket; } catch (UnknownHostException e) { System.err.println(""" + hostname + "" cannot be resolved as a network host."); return null; } catch (IOException e) { System.err .println("An exception occurred while communicating with the TCPServer: " + e.getMessage()); e.printStackTrace(); return null; } } /** * Prints a simple usage string to standard error that describes the command-line arguments for this class. */ private static void printUsage() { System.err .println("TCPClient requires 2 arguments: <Server Host> <Server Port>"); } }