Java - Socket example: EchoClient and EchoServer

来源:互联网 发布:磁贴数据库已损坏 编辑:程序博客网 时间:2024/05/18 00:39
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package chimomo.java.learning;import java.io.*;import java.net.*;/** * * @author Chimomo */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(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);        }    }}

/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */package chimomo.java.learning;import java.net.*;import java.io.*;/** * * @author Chimomo */public class EchoServer {    public static void main(String[] args) throws IOException {        if (args.length != 1) {            System.err.println("Usage: java EchoServer <port number>");            System.exit(1);        }        int portNumber = Integer.parseInt(args[0]);        try (                ServerSocket serverSocket = new ServerSocket(Integer.parseInt(args[0]));                Socket clientSocket = serverSocket.accept();                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);                BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) {            String inputLine;            while ((inputLine = in.readLine()) != null) {                out.println(inputLine);            }        } catch (IOException e) {            System.out.println("Exception caught when trying to listen on port " + portNumber + " or listening for a connection");            System.out.println(e.getMessage());        }    }}

1 0
原创粉丝点击