TCP Server socket not closing when ethernet cable is removed

Hello, I’m creating a TCP server socket using an ethernet connection with following code:

Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, ServerPort));
_serverSocket.Listen(Int32.MaxValue);

Socket newClient = _serverSocket.Accept();

Running in debug, the thread hangs on the .Accept() method until a new client connects, which is all fine. However, when I remove the ethernet cable, the .Accept() method isn’t throwing an exception like I would expect. Instead, it just continues sleeping until the .Accept() method is either called again or the network is reestablished and a client connects.

Is there any way for me to force the .Accept method to end if the network connection is interrupted?

You should subscribe disconnect event when create a network.
When you disconnect cable, there should be an event, try to release your socket in that event?

1 Like

Gotcha, I can do that, thanks.

can you paste here some sample code for me to use.
The ENC28J60 example only has init. sequence
https://docs.ghielectronics.com/software/tinyclr/tutorials/ethernet.html

In the ethernet tutorial there is the “NetworkController_NetworkLinkConnectedChanged” event at the very bottom. This should be invoked every time a network cable is connected or disconnected. In that function is where you would write something like “_serverSocket.Close();”

Be sure to subscribe to it with the line:
networkController.NetworkLinkConnectedChanged += NetworkController_NetworkLinkConnectedChanged;

this function never gets triggered

try a small example and paste into here.