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