Sign in to follow this  
SuperRajar

[.net] NetworkStream WriteLine limit?

Recommended Posts

I'm trying to send a file over TCP with a networkstream. It seems to work only for small files. When I try with bigger files (5-6 Kb) the server doesn't receive enything.
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("XXX.XXX.XXX.XXX", 6667);
NetworkStream ns = tcpclnt.GetStream();
StreamWriter stm = new StreamWriter(ns);

StreamReader fileStream = new StreamReader(Settings.ISA_DIR + "bokabil_d", true);
string line = fileStream.ReadLine();
while (line != null && line != "" && !fileStream.EndOfStream)
{
     stm.WriteLine(line);
     line = fileStream.ReadLine();
     stm.Flush();
}

fileStream.Close();
stm.Close();
ns.Close();
tcpclnt.Close();

Share this post


Link to post
Share on other sites
This should help ya.


private static int SendData(System.Net.Sockets.Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;

byte[] datasize = new byte[4];
datasize = BitConverter.GetBytes(size);
sent = s.Send(datasize);

while (total < size)
{
sent = s.Send(data, total, dataleft, System.Net.Sockets.SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}

private static byte[] RecieveVarData(System.Net.Sockets.Socket s)
{
int total = 0;
int recv;
byte[] datasize = new byte[4];

recv = s.Receive(datasize, 0, 4, 0);
int size = BitConverter.ToInt32(datasize);
int dataleft = size;
byte[] data = new byte[size];

while(total < size)
{
recv = s.Receive(data, total, dataleft, 0);
if(recv == 0)
{
data = Encoding.ASCII.GetBytes("exit");
break;
}
total += recv;
dataleft -= recv;
}
return data;
}



Depending on the TCP settings, you can only send packets of a given size, after that the file becomes fragmented and you won't get the file. This will work for you but it doesn't use streams because they kind of fall apart with something that size. You need to let the receiver know how large the file is going to be and then piece it together from the different parts.

theTroll

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this