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.

_serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

Why are you using this option? It use raises questions…

BTW, the OP never mentioned what board, and if required, how is Ethernet being provided. Makes it difficult for someone to try to reproduce.

Hey Mike, I implemented that line a while back but I’m pretty sure it’s because I wasn’t able to close and reopen the socket without it. Do you think that might be what’s causing this? Are you able to get an exception without it?

The board I’m using is SCM20260D and ethernet is connected to an RJ45 and connected via the ETH PHY pins. Hope that helps.

1 Like

Why would you ever want to close and reopen your listening socket? I don’t think it will make a difference but still worth a try.

Just wanted to update this thread saying that I removed the line Mike was referring to and added an ethernet link ready check to the TCP listener and that seemed to fix it.