Problem Overview
Implement the EchoServer and EchoClient classes, where EchoServer listens on a port number (passed through parameters when it starts) and waits for client access; EchoClient connects to the server based on the incoming server address (IP address or domain name) and port number at startup; After connecting, read the user's input on the command line and transfer the input to EchoServer. After EchoServer is received, return EchoServer received: + user input information; EchoClient receives the return message and outputs it to the command line, and continues. Waiting for user input
1, the client EchoClient.java code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
Package cn.wangbaiyuan; Import java.io.*; Import java.net.*; Import java.util.Scanner; /** * socket communication client class * * @author Wang Baiyuan * */ Public class EchoClient { /** * PORT an initialization port */ Static int PORT = 12340; // connection port /** * HOST an initialization host name */ Static String HOST = "192.168.4.21"; // connection address /** * socket client socket * */ Socket socket; Public EchoClient() throws UnknownHostException, IOException { Socket = new Socket(HOST, PORT); // Create client socket } /** * Implement sending message */ Public void send() { Try { // Client output stream, send a message to the server BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())); // Client input stream to receive server messages BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream())); PrintWriter pw = new PrintWriter(bw, true); // Decorate output stream, refresh in time Scanner in = new Scanner(System.in); // Accept user information String msg = null; While ((msg = in.next()) != null) { Pw.println(msg); // Send to server System.out.println(br.readLine()); // Output message returned by server If (msg.equals("quit")) { Break; // Exit } } } Catch (IOException e) { e.printStackTrace(); } finally { If (null != socket) { Try { Socket.close(); // Disconnect } Catch (IOException e) { e.printStackTrace(); } } } } Public static void main(String[] args) throws UnknownHostException, IOException { BufferedReader strin = new BufferedReader(new InputStreamReader( System.in)); System.out.println("Please enter the connection address:"); HOST = strin.readLine(); System.out.println("Please enter the connection port:"); PORT = Integer.parseInt(strin.readLine()); New EchoClient().send(); } } |
2. Single-threaded server-side EchoServer.java code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
Package cn.wangbaiyuan; Import java.io.BufferedReader; Import java.io.BufferedWriter; Import java.io.IOException; Import java.io.InputStreamReader; Import java.io.OutputStreamWriter; Import java.io.PrintWriter; Import java.net.ServerSocket; Import java.net.Socket; /** * @author Wang Baiyuan *socket communication server class */ Public class EchoServer { /** * */ ServerSocket serverSocket; Private final int PORT = 12340; // port /** * Create a ServerSocket when creating a new EchoServer class * @throws IOException */ Public EchoServer() throws IOException { serverSocket = new ServerSocket(PORT); // Create server socket System.out.println("Server started."); } /** * Start the server socket service and listen for client messages */ Public void servic() { Socket socket = null; While (true) { Try { Socket = serverSocket.accept(); // wait for and remove the user connection and create the socket System.out.println("new connection, connection address:" + socket.getInetAddress() + ":" + socket.getPort()); // client information // Input stream, read client information BufferedReader br = new BufferedReader(new InputStreamReader( socket.getInputStream(), "UTF-8"));// related to the Android client, to set the encoding // Output stream to write information to the client BufferedWriter bw = new BufferedWriter(new OutputStreamWriter( socket.getOutputStream(), "UTF-8")); PrintWriter pw = new PrintWriter(bw, true); // decorate the output stream, true, flush the output buffer every write line, without flush String info = null; // Receive user input information While ((info = br.readLine()) != null) { System.out.println(info); // Output user sent message Pw.println("you said:" + info); // Return the message sent by the user to the client. After the println output, it will automatically refresh the buffer. If (info.equals("quit")) { // exit if user enters "quit" Break; } } } // If the client disconnects, this exception should be caught, but the entire while loop should not be interrupted so that the server can continue to communicate with other clients Catch (IOException e) { e.printStackTrace(); } finally { If (null != socket) { Try { Socket.close(); // Disconnect } Catch (IOException e) { e.printStackTrace(); } } } } } /** * EchoServer main static class, start server-side service at startup * @param args * @throws IOException */ Public static void main(String[] args) throws IOException { New EchoServer().servic(); // Start the service } } |
3, multi-threaded server-side code
ThreadEchoServer.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
Package cn.wangbaiyuan; Import java.io.BufferedReader; Import java.io.BufferedWriter; Import java.io.IOException; Import java.io.InputStreamReader; Import java.io.OutputStreamWriter; Import java.io.PrintWriter; Import java.net.ServerSocket; Import java.net.Socket; Public class ThreadEchoServer { ServerSocket serverSocket; Private final int PORT=1245; //port Public ThreadEchoServer() throws IOException{ serverSocket=new ServerSocket(PORT); //Create a server socket System.out.println("Server started."); } //servic() method Public void service(){ While(true){ Socket socket=null; Try { Socket=serverSocket.accept(); Thread work=new Thread(new Handler(socket)); //Create worker thread for client connection Work.start(); } Catch (IOException e) { e.printStackTrace(); } } } Public static void main(String[] args) throws IOException { New ThreadEchoServer().service(); //Start service } } |
Handler.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
Package cn.wangbaiyuan; Import java.io.*; Import java.net.Socket; Public class Handler implements Runnable { // thread responsible for communicating with a single client Private Socket socket; BufferedReader br; BufferedWriter bw; PrintWriter pw; Public Handler(Socket socket) { This.socket = socket; } Public void initStream() throws IOException { // Initialize input and output stream object methods Br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8")); Bw = new BufferedWriter( New OutputStreamWriter(socket.getOutputStream(),"UTF-8")); Pw = new PrintWriter(bw, true); System.out.println("new connection, connection address:"+socket.getInetAddress()+":"+socket.getPort()); } Public void run() { // Execution contents Try { initStream(); // Initialize input/output stream object String info = null; While (null != (info = br.readLine())) { System.out.println(socket.getInetAddress()+"say:"+info); Pw.println("you said:" + info); // Return the message sent by the user If (info.equals("quit")) { System.out.println(socket.getInetAddress()+" has exited: "+info);// If the user enters "quit" to exit Pw.println("You have left"); Break; } } } Catch (IOException e) { e.printStackTrace(); } finally { If (null != socket) { Try { Socket.close(); } Catch (IOException e) { e.printStackTrace(); } } } } } |
This article has been printed on copyright and is protected by copyright laws. It must not be reproduced without permission.If you need to reprint, please contact the author or visit the copyright to obtain the authorization. If you feel that this article is useful to you, you can click the "Sponsoring Author" below to call the author!
Reprinted Note Source: Baiyuan's Blog>>https://wangbaiyuan.cn/en/ssd8-ex1-socket-communication-java-code-2.html
No Comment