Reputation: 13491
I am using an ElSSLSocket from C#. This is a SecureBlackBox socket. SecureBlackBox is a third party library to handle secure sockets.
I can see that the ElSSLSocket object has a property called 'Socket' so the underlying socket is a normal .NET socket.
My question, is there some kind of event that I can subscribe to so that I can see when the socket disconnects uncleanly? I have a client server connection which often will disconnect. It is hard to see if it is the client or the server, and hard to see the actual cause.
I am pretty sure that there is some logic problems in the application, i.e. this is not caused by network outages or anything like that.
I should also let you know that the disconnections I get are this error,
SocketException - An existing connection was forcibly closed by the remote host
ErrorCode - 10054
If there was any way that I could actually find the cause of that?
Upvotes: 5
Views: 2631
Reputation: 40558
While this is written in C
, you should be able to do the same thing in C#
:
int dummy;
// since you're just testing if the socket is still open for reading you don't
// want it to block, or remove data from the sockets recv buffer
int ret = recv(sockfd, &dummy, sizeof dummy, MSG_DONTWAIT | MSG_PEEK);
if ( ( ret == -1 && ( errno == EAGAIN || errno == EWOULDBLOCK ) )
|| ret > 0 ) {
// socket is still open for reading
else if ( ret == 0 ) {
// socket went through orderly shutdown and is closed for reading
} else {
// there is some error and the socket is likely closed
// check errno
}
Let's say you think it's half closed and you still have data you want to write.
int myData = 0xDEADBEEF;
int ret = send(sockfd, myData, sizeof myData, MSG_NOSIGNAL);
This way, if the socket is completely closed your send won't kill your program with a SIGPIPE
. Instead the call will just return -1 and set errno
to EPIPE
.
Upvotes: 2
Reputation: 456487
Detecting half-open connections is one of the classic socket programming scenarios. The Socket.Connected
property is completely useless, and Socket.Poll
does not work for every situation. It's best to actually send a "heartbeat" message every few seconds.
10054 is one of the common errors. It means the connection has been lost (not cleanly closed). It can be caused by the remote computer shutting down, the remote process exiting, or even an intermediate router being rebooted.
Upvotes: 4
Reputation: 78262
I've found this to work quite well:
Receiving
_socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0
Sending
!_socket.Poll(100, SelectMode.SelectWrite)
Upvotes: 1