Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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!

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...