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