Java socket Programming Development Simple example

Source: Internet
Author: User

1, the following is just a simple example, there is no multithreading, only one (because the scan.nextline () thread will enter the waiting state), use can be based on the specific project function to optimize processing

2, the following code uses 1.8 new features, if you want to test the following code, Java version can not be less than 1.8

    //Client     Public Static voidMain (string[] args) {Try(Scanner scan =NewScanner (system.in); Socket Client=NewSocket ("127.0.0.1", 8484); PrintWriter writer=NewPrintWriter (Client.getoutputstream ()); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (Client.getinputstream ()));) {             while(true) {                //Writer.print (Scan.nextline () + "\ n"); //Writer's Write (Scan.nextline () + "\ n") method//Note: Because the server side is using ReadLine, if it is written in the above two ways, you must add a newline character, otherwise readline is not read the datawriter.println (Scan.nextline ());                Writer.flush ();  while(Reader.ready ()) {System.out.println (Reader.readline ()); }            }        } Catch(IOException e) {e.printstacktrace (); }    }

    //Service Side     Public Static voidMain (string[] args) {Try(Scanner scan =NewScanner (system.in); ServerSocket Server=NewServerSocket (8484); Socket SC=server.accept (); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (Sc.getinputstream ())); PrintWriter writer=NewPrintWriter (Sc.getoutputstream ());) {             while(true) {writer.println (Scan.nextline ());                Writer.flush ();  while(Reader.ready ()) {System.out.println (Reader.readline ()); }            }        } Catch(Exception e) {e.printstacktrace (); }    }

Java socket Programming Development Simple example

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.