The JAVA TCPServer side uses the scanner to read the data without the workaround

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.