创建套接字客户端
import java.io.*; import java.net.*; //from n o w j a v a . c o m public class EchoClient { public static void main(String[] args) throws IOException { if (args.length != 2) { System.err .println("Usage: java EchoClient <host name> <port number>"); System.exit(1); } String hostName = args[0]; int portNumber = Integer.parseInt(args[1]); try (Socket echoSocket = new Socket(hostName, portNumber); PrintWriter out = new PrintWriter( echoSocket.getOutputStream(), true); BufferedReader in = new BufferedReader( new InputStreamReader(echoSocket.getInputStream())); BufferedReader stdIn = new BufferedReader(/*来 自 时 代 J a v a 公 众 号*/ new InputStreamReader(System.in))) { String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } } catch (UnknownHostException e) { System.err.println("Don't know about host " + hostName); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to " + hostName); System.exit(1); } } }