user1065401
user1065401

Reputation: 7

synchronization logic in using network stream

I am using network stream to send a file name (example :"text.txt") and then send the file. the server is supposed to read the name and create a write stream to write the data in. the problem that the server gets the name + data from the file in the read command to get the name only. i think this is unclear. the question i get the file name + some data from the file. code that sends file name then file data:

ASCIIEncoding asci = new ASCIIEncoding();
TcpClient clientSocket = new TcpClient(textBox2.Text, 8880);
NetworkStream networkStream = clientSocket.GetStream();
byte[] b = asci.GetBytes(s);//s is the name of the file
networkStream.Write(b, 0, b.Length);
networkStream.Flush();

while(true)
{
    file = fileStream.Read(fileBuffer,0,fileBuffer.Length);
    networkStream.Write(fileBuffer,0,file);
    if(file == 0) break;
}

the code that the server rec. the name and data with

byte [] buffer2 = new byte[1];
String filename = "";
ASCIIEncoding asci = new ASCIIEncoding();

while (true)
{
    int k = networkStream.Read(buffer2, 0, buffer2.Length);
    filename = filename+asci.GetString(buffer2, 0, k); 
    if (k == 0) break;
}

using (Stream fileStream = File.OpenWrite("C:/Users/Laptop/Documents/" + filename))
{
    while (true)
    {
        thisRead = networkStream.Read(dataByte, 0, blockSize);

        fileStream.Write(dataByte, 0, thisRead);
        if (thisRead == 0) break;

    }

thanks. i think i dont know how to say or illustrate the problem.

Upvotes: 0

Views: 656

Answers (1)

PVitt
PVitt

Reputation: 11760

You have to send something that indicates the end of the filename. The server receives the filename as long as this or these stop characters are not received and it receives the payload afterwards.

For example, HTTP uses \r\n\r\n to mark the end of the HTTP header.

Upvotes: 1

Related Questions