When using Java for socket communication, when the server side uses Scanner's Nextline () method to read data, the data is not read because the scanner is a scanner, it scans the memory of a buffer to scan and read into the data, The data we enter in the console is also stored in the buffer, waiting for the scan to be read by the scanner. This scanner in the scanning process to judge the basis of the stop is "white space", space, carriage return is a blank character. The Nextint () method will read the preceding data when it is scanned to whitespace, but will leave the whitespace "\ r" in the buffer, but the nextline () method will clean up the scanned whitespace when scanning.
In the following server-side program, each time out.println ("Hello"), and then flush a bit because the printwriter is cached. In the input string, include the newline character "\ r \ n", which is responsible for the scanner scanner scan not to the end flag:
1 Try {2 3ServerSocket Server =NewServerSocket (8189);4Socket socket =server.accept ();5InputStream in =Socket.getinputstream ();6OutputStream out =Socket.getoutputstream ();7 8Scanner Scanner =NewScanner (in);9 TenPrintWriter PW =NewPrintWriter (out,true); OnePw.println ("Hello"); A Pw.flush (); - -PW.PRINTLN ("World"); the Pw.flush (); - - BooleanBstop =false; - while(!bstop&&Scanner.hasnextline ()) { + -String mstring =NULL; + Try{ AMstring =scanner.nextline (); at}Catch(Exception e) { - e.printstacktrace (); - } - - if(Mstring.equals ("STOP")) { -Bstop =true; in } - Pw.write (mstring); to Pw.flush (); + } - the}Catch(IOException e) { * $ e.printstacktrace ();Panax Notoginseng}
The JAVA TCPServer side uses the scanner to read the data without the workaround