C#: socket is destroyed when closing application

I have a cash loading machine where through port 8092 it listens for instructions to process. From my application when I send instructions connecting to the socket, as we see in the following code.

enter image description here

Sending and receiving the socket response closes the application and also destroys the socket. (when I query netstat -n it shows 127.0.01:8092 in FAIL_WAIT2 state). Is there a way to not destroy this socket so that it remains listening? Since it is used from another application.

I already tried removing the client.Close() and stream.Close() lines of code but it still destroys the socket.

  • 4

    Please past your code in the question, don’t use screenshots.

    – 

  • If you only know how to make a screenshot – you are wrong here. Learn how to copy/paste code. Also, what you mean “socket is destroyed when closing application” – is that the same logic like “car engine turns off when running out of fuel, help me”? How are we supposed to fix that – and no, not even bothering to look at a screenshot when you are too lazy to extract the source.

    – 

  • 2

    It’s unclear what the expectation or even the question is. The code explicitly closes and disposes the TcpClient after receiving a response

    – 

  • You would typically continuously read from the socket in a loop. Either on a thread or using async/await. But if you do not have any special reason to use raw TCP I would recommend a higher level protocol that can send and receive messages. That will most likely be both easier to use and more reliable. TCP is a fairly low level protocol, and you need to know how to use it correctly.

    – 

  • I’d say the problem lies with the server / software listening on port 8092. A client should be able to create a new socket, send data, receive data, and close the socket connection to the server without stopping the server from listening for new connections. Unless the client is sending a command that is causing the server to stop listening.

    – 




Leave a Comment