Java Socket dead Loop while how to determine client disconnects

Source: Internet
Author: User

A multithreaded server program thread waits for the client's message part code as follows:

Boolean done=clientrequest.isconnected ();//Determine if the client socket is connected

while (done)//client is connected
{
Try
{
input = Clientrequest.getinputstream ();
Binput = new Bufferedinputstream (input);
str = "" + Binput.read ();
if (Binput.read ()! =-1)//If the client has a message, print it out
{
System.out.println (str);
}

}
catch (IOException E)
{
E.printstacktrace ();
}

if (clientrequest.isclosed ())//Determine if the socket is closed
{
done=false;//if off, jump out of the infinite loop (while)
}
}

My code can implement server-to-client communication
The problem is that when the client breaks or exits the above code, it cannot be judged that the socket interrupt cannot jump out of the while Infinite loop

Workaround:

1. while (Binput.read ()! =-1) This method can determine if the client input is null client disconnects can jump out of the loop

2. Use the following method. Add the following code to the dead loop
try {
Socket.sendurgentdata (0);
} catch (IOException e) {
Done= false; If an exception is thrown, then it is disconnected and jumps out of the infinite loop
}

Java Socket dead Loop while how to determine client disconnects

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.