The Socket server and client communication flowchart:
650) this.width=650; "title=" 1554663_201306051010200847.jpg "alt=" wkiom1xt9_yhbegvaac9f18qnfo704.jpg "src="/HTTP/ S3.51cto.com/wyfs02/m00/71/8e/wkiom1xt9_yhbegvaac9f18qnfo704.jpg "/>
Service-Side code:
ServerSocket = new ServerSocket (); Serversocket.setreuseaddress (TRUE); Serversocket.bind (New Inetsocketaddress (port)); Socket = Serversocket.accept (); Socket.setsotimeout (TimeOut); Represents the wait time-out data when the data is received, and this method must be executed before the data is received for validity. Also, when the read () method of the input stream throws Sockettimeoutexception, the socket is still connected, and you can try to read the data again, in milliseconds, with a default value of 0 (which means that it will wait indefinitely and never time out) Socket.setkeepal Ive (false); Indicates whether or not to automatically turn it off in the case of a socket that is idle for a long time in = new BufferedReader (New InputStreamReader (Socket.getinputstream ())); if (In.ready ()) {//stream ready to do processing} in.close () Pool.shutdown ();
Client code: Send Message
Socketclient = new Socket (ServerIP, Port); Socketclient.setsotimeout (0); Socketclient.setkeepalive (FALSE); OS = new Bufferedoutputstream (Socketclient.getoutputstream ()); Os.write (information); Os.flush (); Os.close (); Thread.Sleep (3000);
Reference article:
http://shihuan830619.iteye.com/blog/2041774
This article is from the "Nothing-skywalker" blog, please be sure to keep this source http://tianxingzhe.blog.51cto.com/3390077/1685868
Java Sockets and ServerSocket programming