When listening on the server side is in the loop, it is found that the information of the client is not received normally.
It's OK to put the monitor accept outside the loop. I just learned that it's not very understandable!
Thanks for your help!
public class TcpClient { public static void main(String[] args) { //Create socket Socket s = null; //Create a stream of typing characters BufferedReader reader = null; //Create output character stream BufferedWriter writer = null; try { //Instantiate socket s = new Socket("127.0.0.1",10011); System.out.println("TCP Started please output the information you want to send......"); //Get this socket output stream OutputStream out = s.getOutputStream(); //Instantiate input stream reader = new BufferedReader(new InputStreamReader(System.in)); //Instantiate output stream writer = new BufferedWriter(new OutputStreamWriter(out)); //Save read in information String line = null; while (true){ line = reader.readLine(); writer.write(line); writer.newLine(); writer.flush(); if (line.equals("exit")){ break; } System.out.println("The loop is executed"); } System.out.println("TCP Client end running!"); } catch (IOException e) { e.printStackTrace(); }finally { try { if (s != null){ s.close(); } if (writer != null){ writer.close(); } if (reader != null){ reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
public class TcpServer {
public static void main(String[] args) {
//Create server socket
ServerSocket ss = null;
//Create buffer character stream
BufferedReader reader = null;
try {
//Instantiate socket and bind port
ss = new ServerSocket(10011);
System.out.println("TCP service started..." );
//Listening to client objects
Socket s = ss.accept();
System.out.println("connection successful..." );
//Get the input stream object of the client socket InputStream in = s.getInputStream(); //Replace with buffer character stream reader = new BufferedReader(new InputStreamReader(in)); //Get client ip address InetAddress inetAddress = s.getInetAddress(); String hostAddress = inetAddress.getHostAddress(); while (true) { //Read input stream String line = reader.readLine(); //Set exit signal if (line.equals("exit")){ break; } System.out.println(hostAddress + " Sent:" + line); } System.out.println("TCP End of service!"); } catch (IOException e) { e.printStackTrace(); }finally { try { if (ss !=null){ ss.close(); } if (reader != null){ reader.close(); } } catch (IOException e) { e.printStackTrace(); } } }
}