Socket closed on unexpected closure - java

I'm currently working with sockets in Java.
I have created a listener which will connect to a ServerSocket. This works perfectly fine. However, if my application may encounter unexpected closure, the sockets won't be closed properly. Upon the next run, this will throw a SocketException: socket closed on socket = serversocket.accept();
However, by testing with serversocket.isBound() I've discovered that the serversocket is in fact bound and therefor not closed. Is there any way for me to determine whether it is possible for me to accept the connection and if not, to clear the socket and accept after this?
Thanks in advance.

However, if my application may encounter unexpected closure, the sockets won't be closed properly. Upon the next run, this will throw a SocketException: socket closed on socket = serversocket.accept();
You have that back to front. 'Socket closed' means the socket was closed, not that it wasn't.
However, by testing with serversocket.isBound() I've discovered that the serversocket is in fact bound and therefor not closed.
Wrong. isBound() tells you whether you ever called bind(), explicitly or implicitly. It doesn't change what it returns after you close the socket. Try isOpen() or isClosed(), whichever it is, if you want to know whether the socket is still open.
You need to believe what the exception is telling you. You closed the server socket so now you can't accept from it.
Is there any way for me to determine whether it is possible for me to accept the connection and if not, to clear the socket and accept after this?
It would be more to the point to fix the bug whereby the socket ever got closed in the first place.

Related

Checking Whether Client port is reachable or not for N clients [duplicate]

This question already has answers here:
Java socket API: How to tell if a connection has been closed?
(9 answers)
Closed 7 years ago.
I am developing a Chat system,where i wanted to keep a list of active clients.
So inorder to make sure that the client is active , i will check whether the client is active in that particular port or not.
In order to test client Activity, I considered the following:
getInputStream.read(): I have n number of clients, so I dont want to keep threads active waiting for return statement -1.
isConnected() command is always returning true.
out.checkError() will throw Exception, I dont wish to throw any Exception and get interrupted.
So I have my logic to establish connection through that port and create a file in that client machine. But i am not sure how to do it.
getInputStream.read() - I have n number of clients, so i dont want to keep threads active waiting for return statement
You should use N threads, one per client, like everybody else does. And a socket read timeout.
isConnected() command is always returning true.
It's not a command, it's a method, otherwise correct. It tells you about the state of the Socket, not of the connection. It becomes true once you've connected or accepted the Socket: it never becomes false.
out.checkError() will throw Exception
No it won't. It will return a boolean if there was an IOException writing to the PrintWriter or PrintStream, but it won't tell you what the exception was, and it doesn't apply to read exceptions, so it isn't all that much use. In fact you shouldn't use PrintWriter at all over a network for that reason, you should use BufferedWriter.
Use a thread per client.
I don't wish to throw any Exception
Bad luck, that's the only way you're going to detect a connection abort.
and get interrupted.
I don't know what this means.

Difference between isConnected and isClosed [duplicate]

This question already has answers here:
How can a socket be both connected and closed?
(1 answer)
Java socket API: How to tell if a connection has been closed?
(9 answers)
Closed 9 years ago.
I would have assumed that calling isConnected() on a socket would tell me whether if is connected to the other side or not.
Returns: true if the socket successfuly connected to a server
but after checking and then calling flush() on the socket I get
java.net.SocketException: Broken pipe
How is isConnected different than isClosed, and what is the real behavior of each?
How do I tell if the other side if officially closed without writing anything to the streams, or creating new connections? Is there even a way?
I would have assumed that calling isConnected() on a socket would tell me whether if is connected to the other side or not.
Wrong. It tells you whether you ever connected this Socket. It doesn't tell you about the state of the connection.
Returns: true if the socket successfuly connected to a server
Note that it doesn't say 'is currently connected' to a server.
How is isConnected different than isClosed, and what is the real behavior of each?
The real behaviour of both is that they tell you what you have done to the socket, not what the state of the connection is.
How do I tell if the other side if officially closed without writing anything to the streams, or creating new connections? Is there even a way?
No there isn't. If the peer closed normally, a read will return an EOS indication (read() returns -1, readLine() retuns null, readXXX() for any other XXX throws EOFException). A write will throw an IOException 'connect reset' or 'broken pipe' depending on your platform. TCP doesn't support anything in the nature of a 'dial tone', so absent a pending write there is no current connection status to enquire on.

Nonsensical Java exceptions? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Does close ever throw an IOException?
Can someone explain to me why socket.close() throws an IOException in Java? I seriously can not figure out how closing a socket is any different from telling the runtime to go right ahead and clean up the resources that the socket is holding onto. Is there another way of not leaking memory and cleaning up socket resources that I don't know of?
It turns out that in many cases the only time that an extant error can be communicated to the calling code is when close() is called. For example, if you have sent a UDP packet that has been rejected by the receiving computer, the only chance you have to find out about it is the next time you use that socket. If the next time you use that socket is to close it, that's when you get the exception. Note that the exception does not prevent the socket from closing, which seems to be what you're asking.
One case ... a socket that has not been opened.

how to know a Java Socket is dead

I use a Java Socket object in my client application. I need to know when the line to the server is broken, or if any event caused the socket to be dead.
I see two methods:
catching SocketException when writing in or reading from the socket, considering these exceptions kill the socket
when catching these exceptions, checking the Socket.isClosed() method to know if it killed the socket
Does any of these methods guarantee I'll know when the socket is dead and won't work again, even if a temporary problem on the line is solved?
Can we except a (Socket)Exception thrown during an operation on a socket to imply the socket is dead?
Is there a better method to know this?
At least:
Receiving an exception does NOT mean the socket is always dead, from Socket.setSoTimeout() javadoc:
If the timeout expires [on a read for instance, a java.net.SocketTimeoutException is raised, though the Socket is still valid.
The closed flag of the socket seems to be set only when the Socket.close() method is called, so I would not rely on it.
This is usually done by a timeout. This is mandatory if you don't trust the other side (like every time). Without a timeout, an attacker can DoS your application easily by opening connections without sending anything. Once you hit the socket limit of your system, the application might even crash...
A "Dead Socket" can be considered as an abnormal status. It is just a errornous bahaviour. So I don't think you can handle this situation effectively.
Since there is nothing like a keep-alive between sockets, you will learn that the connection is broken not until ,next time you try to write onto this socket.

How do you handle Socket Disconnecting in Java? [duplicate]

This question already has answers here:
Java socket API: How to tell if a connection has been closed?
(9 answers)
Closed 1 year ago.
Hey all. I have a server written in java using the ServerSocket and Socket classes.
I want to be able to detect and handle disconnects, and then reconnect a new client if necessary.
What is the proper procedure to detect client disconnections, close the socket, and then accept new clients?
Presumably, you're reading from the socket, perhaps using a wrapper over the input stream, such as a BufferedReader. In this case, you can detect the end-of-stream when the corresponding read operation returns -1 (for raw read() calls), or null (for readLine() calls).
Certain operations will cause a SocketException when performed on a closed socket, which you will also need to deal with appropriately.
The only safe way to detect the other end has gone is to send heartbeats periodically and have the other end to timeout based on a lack of a heartbeat.
Is it just me, or has nobody noticed that the JavaDoc states a method under ServerSocket api, which allows us to obtain a boolean based on the closed state of the serversocket?
you can just loop every few seconds to check the state of it:
if(!serverSocket.isClosed()){
// whatever you want to do if the serverSocket is connected
}else{
// treat a disconnected serverSocket
}
EDIT: Just reading your question again, it seems that you require the server to just continually search for connections and if the client disconnects, it should be able to re-detect when the client attempts to re-connect. should'nt that just be your solution in the first place?
Have a server that is listening, once it picks up a client connection, it should pass it to a worker thread object and launch it to operate asynchronously. Then the server can just loop back to listening for new connections. If the client disconnects, the launched thread should die and when it reconnects, a new thread is launched again to handle the new connection.
Jenkov provides a great example of this implementation.

Categories

Resources