Answer the question
In order to leave comments, you need to log in
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:
// Отправляем:
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);
// Код для приёма файла на стороне сервера
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());
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question