Вопрос

I have a major problem with my code. Or with system. Here is the client code in C#:

TcpClient client = new TcpClient("192.168.1.254", 19999);
NetworkStream nstream = client.GetStream();
Console.WriteLine("Connected.");
Stream stream = new FileStream("test.dat", FileMode.Create, FileAccess.Write);
int counter = 0;
byte[] buffer = new byte[1024];
while ((counter = nstream.Read(buffer, 0, 1024)) > 0)
{
    stream.Write(buffer, 0, counter);
}
stream.Close();
nstream.Close();
client.Close();
Console.WriteLine("Done here.");

This application works with a server, written in python. No rocket science here. Client connects, server immediately sends data in loop till the end and the socket closes. The problem is, that on my machine this application always stops receiving data after 5 - 7 kB. It stops and (as debugger shows) hangs on read method. This is happening only on my machine (Windows 7 x64 from MSDN, visual studio 2013 express, .net 4.5.1). Tested this application also on my machine but on Linux, with mono and on some other Windows machines. Everywhere it works but sadly not here. I guess that's a problem with my system, so here is what I tried so far:

  • running application without debugger

  • reinstalling visual studio

  • reinstalling .NET framework

  • turning windows firewall and AV off

  • changing target framework to previous versions (3, 3.5)

Unfortunately, reinstalling OS is not possible. I have to make this work on my system, but I'm running out of options. I don't even know what is causing that issue. What else can I check?

Это было полезно?

Решение

The NetworkStream.Read method, when called with no bytes available, will block until either bytes become available or the connection is closed. So, you might be better off to either 1) devise a protocol where you know how many bytes are coming in advance, then stop reading when you've read that many bytes, or 2) close the connection after a timeout of inactivity. Note that 1) is the only way to properly code this, 2) will give you partial data if network hiccups occur.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top