I have a simple server that receives a string from a client and prints it on the screen. I also have a simple client sending data and closing:
static void Main()
{
var client = new TcpClient("localhost", 26140);
var stream = client.GetStream();
Byte[] data = System.Text.Encoding.UTF8.GetBytes("CALC qwer");
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
And with uncommented string 'Thread.Sleep (100)' works fine. But when commenting, sometimes (1 out of 5-10 starts) the client does not send the line. Watching wirehark and netstat, I noticed that the client sends SYN, an ACK packet, establishes a connection and exits without sending anything and without closing the socket.
Can anyone explain this behavior? Why does sleep help? What am I doing wrong?
UPD:
With this code example, adding flush () before closing really works, thanks Fox32.
But after that I returned to the source code:
var client = new TcpClient("localhost", 26140);
client.NoDelay = true;
var stream = client.GetStream();
var writer = new StreamWriter(stream);
writer.WriteLine("CALC qwer");
writer.Flush();
stream.Flush();
stream.Close();
client.Close();
, NoDelay. - StreamWriter ?
UPD:
:
static void Main(string[] args)
{
(new Server(26140)).Run();
}
Server:
public void Run()
{
var listener = new TcpListener(IPAddress.Any, port);
listener.Start();
while (true)
{
try
{
var client = listener.AcceptTcpClient();
Console.WriteLine("Client accepted: " + client.Client.RemoteEndPoint);
var stream = client.GetStream();
stream.ReadTimeout = 2000;
byte[] buffer = new byte[1000];
stream.Read(buffer, 0, 1000);
var s = Encoding.UTF8.GetString(buffer);
Console.WriteLine(s);
}
catch (Exception ex)
{
Console.WriteLine("ERROR! " + ex.Message);
}
}
}
UPD:
Sleep (1) 30-50 , .
Sleep (10), , , .
, , .