Java for simple socket communication

Source: Internet
Author: User

Today I learned how to implement socket communication in Java, the difficulty is on the IO, because Java is already perfect for socket encapsulation.

Today the code spent the whole night debugging, the main reason is the flush problem of IO and command line how to run the class with the package, but finally the problem is basically solved, put the code for your reference

Server
 Public classTCPServer { Public Static voidMain (string[] args)throwsException {serversocket server=NewServerSocket (9091); Try{Socket Client=server.accept (); Try{BufferedReader input=NewBufferedReader (NewInputStreamReader (Client.getinputstream ())); BooleanFlag =true; intCount = 1;  while(flag) {SYSTEM.OUT.PRINTLN (the client is going to start to flirt, this is the first+ Count +times!                    ); Count++; String Line=Input.readline (); SYSTEM.OUT.PRINTLN (client says:+Line ); if(Line.equals (exit)) {flag=false; SYSTEM.OUT.PRINTLN (the client does not want to play!)                    ); } Else{System.out.println (client says:+Line ); }                 }            } finally{client.close (); }                     } finally{server.close (); }    }}
Client
 Public classTcpClient { Public Static voidMain (string[] args)throwsException {Socket client=NewSocket (127.0.0.1, 9091); Try{printwriter output=NewPrintWriter (Client.getoutputstream (),true); Scanner Cin=NewScanner (system.in);             String words;  while(Cin.hasnext ()) {words=Cin.nextline ();                 OUTPUT.PRINTLN (words); System.out.println (writes out the data:+words);        } cin.close (); } finally{client.close (); }    }}

Java for simple socket communication

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.