Home > Back-end >  How to let the socket end disconnected directly no longer connect reset;
How to let the socket end disconnected directly no longer connect reset;

Time:10-26

The Socket server and client connection
Server:
ServerSocket SERVER=new ServerSocket (11111);
System. The out. Println (" server is started, wait for users to connect -- -- -- -- -- -- -- -- -- ");
While (true) {

//connect the client
The Socket Socket=SERVER. The accept ();

The ObjectOutputStream oos=new ObjectOutputStream (socket. GetOutputStream ());
ObjectInputStream ois=new ObjectInputStream (socket. GetInputStream ());


Es. The execute (new User (oos, ois, socket));

}

User threads: the while (true) {ois. ReadObject ()}

Client: Socket Socket=null;
Try {
The socket=new socket (" 192.168.10.10 ", 11111);
The ObjectOutputStream oos=new ObjectOutputStream (socket. GetOutputStream ());
ObjectInputStream ois=new ObjectInputStream (socket. GetInputStream ());

While (true) {
Try {
Thread.sleep (1000);
{} catch InterruptedException (e)
e.printStackTrace();
}
}

} the catch (IOException e) {
e.printStackTrace();
}

When closing the client server has been throwing an exception java.net.SocketException: Connection reset is to reconnect the mean?
How to let the client closed end directly to disconnect the server directly free memory on both ends?

CodePudding user response:

Pass the User the socket threads
User threads: the while (true) {
If (socket. IsClosed () | |! Socket. IsConnected) {//whether the socket closed or not unicom
break;
}
Ois. ReadObject ();
}

CodePudding user response:

reference 1st floor qybao response:
pass socket to User thread
User threads: the while (true) {
If (socket. IsClosed () | |! Socket. IsConnected) {//whether the socket closed or not unicom
break;
}
Ois. ReadObject ();
}

Just tried it on or not;
Threads should be blocked to ois. The readObject ();
So even if the socket was closed in readObject ();
Not after the above judgment

CodePudding user response:

Then you setSoTimeout set the timeout, then catch exceptions Java.net.SocketTimeoutException after using the above methods to determine whether a socket connection state,
  • Related