Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] NetworkStream WriteLine limit?

Started by SuperRajar Oct 11, 2008 at 9:28 AM 0 replies 1.4k views
Original Post
SuperRajar
SuperRajar
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();

TheTroll
TheTroll
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.