ServerSocket (TCP/IP protocol) __java

Source: Internet
Author: User

Server-Side  
1      Public Static voidMain (string[] args)throwsIOException {2SYSTEM.OUT.PRINTLN ("Server on Monitoring");3ServerSocket server=NewServerSocket (6666);4Socket client =server.accept ();5SYSTEM.OUT.PRINTLN ("Connection succeeded");6          while(true) {//loop receive7             byte[] Data=New byte[1024];8             intCount =Client.getinputstream (). read (data);9String msg=NewString (Data,0,count, "Utf-8");Ten             if("Exit". Equals (msg)) One                  Break; A             Else - System.out.println (msg); -         } the client.close (); -Server.close (); -}
User-side
1      Public Static void throws unknownhostexception, IOException {  2         SYSTEM.OUT.PRINTLN ("Client start Access");         3         New Socket ("1.1.1.1", 6666); Parameters are required for the ServerSocket server: IP and port number, port number is the port number set by the ServerSocket server
4Scanner Scanner =NewScanner (system.in);
5      while(true) {//Loop send
6System.out.println ("Please Enter:");
7String x=Scanner.next ();
8         byte[] Data=x.getbytes ("Utf-8");
9 Client.getoutputstream (). write (data);
Ten         if("End". Equals (x))
One        Break;
A }
- Client.close ();
-}
test method:

Build two classes with the main method and put the code into the class separately. You can start two classes with a DOS command in CMD, or you can start with tomcate. (Note: Start the server-side main method before starting the user-side code)

ServerSocket (TCP/IP protocol) __java

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.