This example only demonstrates simple functions, and the code is not rigorous, but only explains how the client can implement simple code connecting to the server.
The code tests the compilation and running environment under the integrated Eclipse tool as shown in the figure below:
Client echoClient.java code:
package com.zhengzz.echo;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter ;import java.net.Socket;import java.net.UnknownHostException;class EchoC{ private Socket socket; public EchoC() { // TODO Auto-generated constructor stub try { socket = new Socket("localhost", 60000); } catch (Unkno wnHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void Client() { try { BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); Pr intWriter pw = new PrintWriter(socket.getOutputStream(), true) ; BufferedReader lbr = new BufferedReader(new InputStreamReader(System.in)); String linestr = null; while ((linestr = lbr.readLine()) != null) { pw.println (linestr); System.out.println( br.readLine()); if (linestr.equals("bye#")) { break; } } } catch (IOException e) { e.printStackTrace(); } }}public class echoClient { public c static void main(String [] args) { new EchoC().Client(); }}Server echoServer.java code:
package com.zhengzz.echo;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter ;import java.net.ServerSocket;import java.net.Socket;class EchoS{ private ServerSocket serverSocket; public EchoS() { try { serverSocket = new ServerSocket(60000); } catch (IOException e) { e.printStackTrace( ); } } public void Server() { while (true) { try { Socket socket = serverSocket.accept(); System.out.println("client:" + socket.getInetAddress() + ":" + socket.getLocalPort()); BufferedReader br = ne w BufferedReader(new InputStreamReader(socket.getInputStream() )); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); String linestr; while ((linestr = br.readLine()) != null) { System.out.println( linestr); pw.println( "--->" + linestr); } } catch (IOException e) { System.out.println("Connection disconnected: ("); } }}} public class echoServer { public static void main(String[] ar gs ) { new EchoS().Server(); }}My direct debugging results under the Eclipse tool are as follows:
Let's take a look at an example of HelloWord-level Java Socket communication. Communication process:
First start the Server side and enter a dead loop to keep listening to whether there is a connection request for a certain port. Then run the Client side, the client issues a connection request, and the server listens to the request and sends back an acceptance message to the client. The connection is established, and a thread is started to process the request, and then continues to listen to other requests in a dead loop. After the client enters the string, press Enter to send data to the server. The server reads the data and responds to the client data. After the request is processed this time, the started thread disappears. If the client receives return data other than "OK", it will send the connection request again and send the data, and the server will start a thread again for the connection to respond. . . The client exits until the return data received by the client is "OK".
Server source code:
package com.defonds.socket.begin; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.In putStreamReader; import java.net.ServerSocket; import java.net.Socket ; public class Server { public static final int PORT = 12345;//The port number of listening public static void main(String[] args) { System.out.println("Server startup.../n"); Server server = new Server(); server.init(); } public void init() { try { ServerSocket serverSocket = new ServerSocket(PORT); while (true) { // Once there is a blockage, it means that the server and the client have been connected Connect Socket client = serverSocket.accept(); // Handle this connection new HandlerThread(client); } } catch (Exception e) { System.out.println("Server exception: " + e.getMessage()); } } private class HandlerThread implements Runnable { private Socket socket; public HandlerThread(Socket client) { socket = client; new Thread(this).start(); } pu blic void run() { try { // Read client data DataInputStream input = new DataInputStream(socket.getInputStream()); String clientInputStr = input.readUTF();// Here you need to pay attention to the corresponding method of the client output stream, otherwise EOFException will be thrown // Process client data System.out. println(" Content sent by the client: " + clientInputStr); // Reply to the client DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.print("Please enter:/t"); // Send A line entered by the keyboard String s = new BufferedReader(new InputStreamReader(System.in)).readLine(); out.writeUTF(s); out.close(); input.close(); } catch (Exc episode e) { System .out.println("Server run exception: " + e.getMessage()); } finally { if (socket != null) { try { socket.close(); } catch (Exception e) { socket = null; System .out.println("Server finally exception:" + e.getMessage()); } } } } } } } }Client source code:
package com.defonds.socket.begin; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.I OException; import java.io.InputStreamReader; import java.net.Socket ; public class Client { public static final String IP_ADDR = "localhost";//Server address public static final int PORT = 12345;//Server port number public static void main(St ring[] args) { System.out.println(" Client starts..."); System.out.println("When the server character is /"OK/" is received, the client will terminate /n"); while (true) { Socket socket = null; try { //Create a stream socket and connect it to the specified port number on the specified host socket = new Socket(IP_ADDR, PORT); //Read server-side data DataInputStream input = new DataInputStream(socket.getInputStrea m() ); //Send data to the server DataOutputStream out = new DataOutputStream(socket.getOutputStream()); System.out.print("Please enter: /t"); String str = new BufferedReader( new InputStreamReader(System.in) ).readLine(); out.writeUTF(str); String ret = input.readUTF(); System.out.println("The server returns: " + ret); // If "OK" is received, disconnect if ("OK".equals(ret)) { System.out.println("Client will close the connection"); Thread.sleep(500); break; } out.close(); input.close( ); } catch (Exception e) { System.out.println("Client Exception:" + e.getMessage()); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { socket = null; System.out.println("Client finally exception:" + e.getMessage()); } } } } } } } } } } }Note: When the Socket output stream writes data method is writeUTF, the input stream needs to use readUTF to read related data. Otherwise, an EOFException exception will be thrown.