Java Sockets and ServerSocket programming

Source: Internet
Author: User



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

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.