Sharpov

Sharpov

  • NA
  • 5
  • 0

[C# .NET 2.0] Weird behaviour with Close method of TcpClient class

Jul 22 2009 12:11 PM
Hello, I send some data to a server (but don't wait for any answer) with this piece of code: private void Send() { TcpClient client = null; try { client = new TcpClient(s_host, s_port); } catch { PushLog("Failed to connect to {0}:{1}...", s_host, s_port); return; } NetworkStream networkStream = client.GetStream(); StreamWriter streamWriter = new StreamWriter(networkStream); streamWriter.AutoFlush = true; streamWriter.NewLine = "\r\n"; try { string req = string.Format("foo", s_loginName); streamWriter.WriteLine("POST /myendpoint?message=foo HTTP/1.0\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 0\r\n"); } catch (Exception err) { PushLog("Failed to send message...\n-> {0}", err.Message); } finally { networkStream.Dispose(); client.Close(); } } The problem I have with this code is that the server receives my message approximatively 1 time out of 10. But if I remove the finally block (NetworkStream and TcpClient closing), the server receives my message every time. What am I doing wrong here? I'm pretty sure I have to close my connection and I read in some doc that the underlying NetworkStream should also be closed. Why is it working sometimes? Should I specify a SendTimeout value? Thanks for your help!

Answers (1)