How can I find out when the socket is disconnected

I am using ElSSLSocket from C #. This is a SecureBlackBox socket. SecureBlackBox is a third-party library for handling secure sockets.

I see that the ElSSLSocket object has the "Socket" property, so the main socket is a regular .NET socket.

My question is, is there some kind of event that I can subscribe to so that I can see when the socket is disconnected uncleanly? I have a connection to a client server that often disconnects. It is difficult to understand whether this is a client or server, and it is difficult to see the actual reason.

I am sure that there are some logical problems in the application, i.e. it is not caused by network outages or something like that.

I must also tell you that disconnected messages are this error,

SocketException - an existing connection was forcibly closed by the remote host

ErrorCode - 10054

If any way could find the reason for this?

+4
source share
3 answers

Semi-open connection discovery is one of the classic socket programming scenarios . The Socket.Connected property Socket.Connected completely useless, and Socket.Poll does not work for every situation. It’s best to send a heartbeat message every few seconds.

10054 is one of the common mistakes . This means that the connection was lost (not cleanly closed). This can be caused by a shutdown of the remote computer, exit of the remote process, or even an intermediate router.

+4
source

While this is written in C , you should do the same 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 } 

Say you think it is half closed and you still have the data you want to write.

 int myData = 0xDEADBEEF; int ret = send(sockfd, myData, sizeof myData, MSG_NOSIGNAL); 

Thus, if the socket is completely closed, your transfer will not kill your program with SIGPIPE . Instead, the call will simply return -1 and set errno to EPIPE .

+2
source

I found this to work very well:

Reception

 _socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0 

Dispatch

 !_socket.Poll(100, SelectMode.SelectWrite) 
+1
source

Source: https://habr.com/ru/post/1313463/


All Articles