TcpClient Close method problem

Sharpov

New member
Joined
Jul 23, 2009
Messages
1
Hello,

I send some data to a server (but dont wait for any answer) with this piece of code:

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?
Im 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!
 
Have you tried manually calling Flush on the StreamWriter before disposing of the underlying stream, just to see if that makes a difference?
 
Back
Top