I am writing a small (C #) client application that sends data using a TCP / IP connection to a remote server. I use the standard .Net TcpClient object and want to leave the connection open from the end of the client, as I regularly send data packets to the server. However, it is possible that the server might close the connection, in which case I need to know how to reconnect before sending the next packet.
Using Wireshark, I see (only) the following dialog when the server terminates the connection:
server >>> FIN, ACK
ACK <<< client
What I don't see is my client, which responds with its own FIN to complete the connection. As a result, my client program detects that the connection was not sent after sending the next data packet.
Is it possible to configure TcpClient or its underlying Socket to complete the disconnection and provide some feedback so that my client code knows I need to reconnect before sending the next packet?
Added in response to the comment below: My submit code is very simple - an object that supports the TcpClient and NetworkStream member variables has a member function containing (essentially) the following:
bool sent = false; byte[] buffer = Encoding.UTF8.GetBytes(dataString); while (!sent) { try { m_outStream.Write(buffer, 0, buffer.Length); sent = true; } catch (Exception ex) { if (m_outStream != null) { m_outStream.Dispose(); } m_client = new TcpClient(AddressFamily.InterNetwork); m_client.Connect(ipAddress, ipPort); m_outStream = m_client.GetStream(); } }
When initializing m_client and m_outStream, it simply performs one pass each time. Then, using Wireshark, I see how the server sends a packet with FIN, ACK flags, to which the client responds with ACK .
The next time my function is called, the data is sent using PSH, ACK , and the server responds with RST, ACK , but does not read the incoming data. The client does not raise any exceptions.
Then I call my function a second time, and an exception is raised causing the connection to restart.