E
E
Eugene2019-04-01 16:27:32
C++ / C#
Eugene, 2019-04-01 16:27:32

What is the role of streams (Stream) and how do they work in transferring data over a local network (via Socket)?

Hello! I am writing a client-server application. Task: transfer a file from the server to the client (at the request of the client). File of any format and size. I wrote client-server applications, but very simple ones, and it was copy-paste with a few modifications. When searching on the Internet, I found codes in which the NetworkStream, BinaryReader, FileStream, etc. classes constantly appear. Here are the codes:

Option number 1
// Отправляем:
SInfo.StringsWriter.Write("123.exe");
SInfo.StringsWriter.Write("C:");
string FileName = @"D:\Шара\Gish_v1.3_RUS.exe";
FileStream Stream = File.OpenRead(FileName);
byte[] Buffer = new byte[128];
byte[] BytesInArray;
int BytesRead = -1;
while (BytesRead != 0)
{
BytesRead = Stream.Read(Buffer, 4, 124);
BytesInArray = BitConverter.GetBytes(BytesRead);
BytesInArray.CopyTo(Buffer, 0);
SInfo.StringsWriter.Write(Buffer);
}
Stream.Close();
Console.WriteLine("Transfer complete");
 
// и получаем:
ClInfo[IDClient].StringsWriter.Write("Name");
string FileName = ClInfo[IDClient].StringsReader.ReadString();
LogWrite("Имя файла определенно - " + FileName, ConsoleColor.DarkYellow);
ClInfo[IDClient].StringsWriter.Write("Folder");
string FolderName = ClInfo[IDClient].StringsReader.ReadString();
LogWrite("Путь к папке определен - " + FolderName, ConsoleColor.DarkYellow);
FileStream Writing = File.OpenWrite(FolderName + @"\" + FileName);
byte[] Buffer = new byte[128];
byte[] BytesInArray = BitConverter.GetBytes(-1);
BytesInArray.CopyTo(Buffer, 0);
LogWrite("Начинаю прием файла " + FileName, ConsoleColor.DarkYellow);
while (BitConverter.ToInt32(Buffer, 0) != 0)
{
Buffer = ClInfo[IDClient].StringsReader.ReadBytes(128);
Writing.Write(Buffer, 4, BitConverter.ToInt32(Buffer, 0));
}
LogWrite("Файл " + FileName + " успешно получен!", ConsoleColor.DarkGreen);
Writing.Close();
LogWrite("Файл " + FileName + " сохранен в папке " + FolderName + "!", ConsoleColor.DarkGreen);

Option number 2
// Код для приёма файла на стороне сервера
        static void uploadFile(NetworkStream ns)
        {
            byte[] buf = new byte[1024];
            int count;
            FileStream fs = new FileStream("uploadFile.txt", FileMode.Open);
            BinaryReader br = new BinaryReader(fs);
            fs.Close();
 
            byte[] sizeFile = BitConverter.GetBytes(fs.Length);
            // Передаем размер файла
            ns.Write(sizeFile, 0, sizeFile.Length);
 
            Thread.Sleep(500);
            BinaryFormatter formater = new BinaryFormatter();
 
            while ((count = br.Read(buf, 0, 1024)) > 0)
            {
                formater.Serialize(ns, buf);
            }
        }
 
        // Код для передачи файла на стороне клиента
        static void sendFile(Socket client, NetworkStream ns)
        {
            byte[] buffe = new byte[client.ReceiveBufferSize];
            // ns = NetworkStream
            ns.Read(buffe, 0, buffe.Length);
            int sizeFile = BitConverter.ToInt32(buffe, 0);
 
            MemoryStream ms = new MemoryStream();
            BinaryFormatter formater = new BinaryFormatter();
 
            while (sizeFile > ms.Length)
            {
                ms.Write((byte[])formater.Deserialize(ns), 0, 1024);
                //sizeFile -= 1024;
            }
            File.WriteAllBytes("sendFile.txt", ms.ToArray());
        }

How I see the principle of sending a file over the network: Before sending a file, a connection is established and the file is sent, but before sending, it is converted to bytes. And then I can't figure out how it works... Is the file converted to bytes? Is the whole file converted or just a part of it? And how are these parts sent (if part)? Or how is the whole file sent? In general, "here are all my powers ...".

Question: How does it all work? I see cycles in which bytes are written to the stream (stream), as I understand it. But I never see that they would be sent (that is, the method (Socket) client.Send("And here, for example, send a stream")). And in general I don’t see anything that says that the socket is somehow used, I see manipulations with bytes (as I suppose),Please explain how it works? I will be very grateful! And here is the stream and how this stream affects the sending of bytes over the network. And without the Send method. And what is the meaning of the Send method? When the Send method is called, is the stream sent?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2019-04-01
@petermzg

Stream is just a convenient abstract class for working with data streams.
The TcpClient class based on it implements its own class, which can be obtained as follows
And now all the bytes that are written to this stream are sent via the overridden Write, WriteAsync, WriteByte, BeginWrite methods over the established network connection.
PS: Any file is originally a set of bytes, so no conversions are required, as in your example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question