Skip to content

C# System.Net.Sockets.TcpListener Stop, Start problem when client connection is active.

Hello.

I'm making C# block with System.Net.Sockets.TcpListener and TcpClient connection. TcpListeneris created and stoped in System.Threading.Thread not to block PLC cycle. But if I try to close TcpClient connection (from server side) and immediately stop TcpListeneris. Then creating a new TcpListeneris and starting it. I get an SocketException with message: "Exception of type \'System.Net.Sockets.SocketException\' was thrown." For some while (few min) and then it creates and starts like nothing happened.

But If I close TcpClient connection from client side, then Stopping and starting TcpListeneris is instant.

Is there a way to fix this?

Comments

  • Hello RaimondasProrega,

    the Stop method of TcpListener closes the listener. Any unaccepted connection requests in the queue will be lost. Remote hosts waiting for a connection to be accepted will throw a SocketException. Normally the TcpListener runs permanently and connection close will be executed on the TcpClient side.

    When the error occurs, the server stops the socket connection e.g. in context of an exception: TcpListener.Stop Method (System.Net.Sockets) | Microsoft Learn

    The system needs some time to stop the socket and freeing this resource. Please program some (sleep) time before creating the new socket. I would like to recommend to implement a state machine.

    I hope this info can help you to mplement the FB's, if not please contact the phoenix contact support department in your country.

    BR Eduard

Sign In or Register to comment.