An example of a Java Socket server and client communication

Source: Internet
Author: User
Tags getmessage

http://blog.csdn.net/defonds/article/details/7971259

A small example of a service-side communication that multiple clients correspond to.

Service side and client code:

 Public classServer {/*** Listening Ports*/     Public Static Final intPORT = 12345;  Public Static voidMain (string[] args) {System.out.println ("Server Start" ""); Server server=NewServer ();    Server.init (); }     Public voidinit () {Try{serversocket ServerSocket=NewServerSocket (PORT);  while(true){                //Once there is a blockage, the server and the client get a connectionSocket client =serversocket.accept (); Newhandlerthread (client); }        } Catch(Exception e) {e.printstacktrace (); }    }    Private classHandlerthreadImplementsrunnable{Privatesocket socket;  PublicHandlerthread (socket socket) { This. Socket =socket; NewThread ( This). Start (); } @Override Public voidrun () {Try {                //Read client dataDataInputStream input =NewDataInputStream (Socket.getinputstream ()); //here to pay attention and the client output stream write method corresponds, otherwise it will throw EofexceptionString Clientinputstr =Input.readutf (); //processing data sent by the clientSystem.out.println ("What the client sent over:" +clientinputstr); //want the client to send a messageDataOutputStream out =NewDataOutputStream (Socket.getoutputstream ()); System.out.println ("Please enter: \ t"); String outstr=NewBufferedReader (NewInputStreamReader (system.in)). ReadLine ();                Out.writeutf (OUTSTR);                Out.close ();            Input.close (); } Catch(IOException e) {System.out.println ("Server Exception:" +e.getmessage ()); }finally {                if(Socket! =NULL) {                    Try{socket.close (); } Catch(Exception e) {socket=NULL; System.out.println ("Server End Finally exception:" +e.getmessage ()); }                }            }        }    }}
 Public classClient { Public Static Final intPORT = 12345;  Public Static FinalString ip_addr = "localhost";  Public Static voidMain (string[] args) {System.out.println ("Client Enablement" ""); System.out.println ("When the server-side character is received as \" Ok\ ", the client terminates \ n");  while(true) {Socket Socket=NULL; Try {                //create a stream socket and connect it to the specified port number on the specified hostSocket =NewSocket (Ip_addr,port); Socket.setsotimeout (5000); //Read server-side dataDataInputStream input =NewDataInputStream (Socket.getinputstream ()); //send data to server sideDataOutputStream out =NewDataOutputStream (Socket.getoutputstream ()); System.out.print ("Please enter: \ t"); String Str=NewBufferedReader (NewInputStreamReader (system.in)). ReadLine ();                Out.writeutf (str); String ret=Input.readutf (); System.out.println ("The server side returned is:" +ret); if(Ret.endswith ("OK") {System.out.println ("The client will close the connection"); Thread.Sleep (500);  Break;                } out.close ();            Input.close (); } Catch(IOException |interruptedexception e)            {E.printstacktrace (); }finally {                if(Socket! =NULL) {                    Try{socket.close (); } Catch(IOException e) {socket=NULL; System.out.println ("Client finally exception:" +e.getmessage ()); }                }            }        }    }}

An example of a Java Socket server and client 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.