matriz de bytes misturado depois usando TcpClient e TcpListener
-
18-09-2019 - |
Pergunta
Eu quero usar o TcpClient e TcpListener para enviar um arquivo mp3 em uma rede. Eu implementei uma solução deste utilizando soquetes, mas houve alguns problemas assim que eu estou investigando uma melhor maneira nova / enviar um arquivo.
I criar uma matriz de bytes que tem esta aparência: length_of_filename | filename | arquivo
Isto deve então ser transmitida usando as classes acima mencionadas, ainda no lado do servidor a matriz de bytes que eu li é completamente desarrumada e eu não sei por que.
O método que eu uso para enviar:
public static void Send(String filePath)
{
try
{
IPEndPoint endPoint = new IPEndPoint(Settings.IpAddress, Settings.Port + 1);
Byte[] fileData = File.ReadAllBytes(filePath);
FileInfo fi = new FileInfo(filePath);
List<byte> dataToSend = new List<byte>();
dataToSend.AddRange(BitConverter.GetBytes(Encoding.Unicode.GetByteCount(fi.Name))); // length of filename
dataToSend.AddRange(Encoding.Unicode.GetBytes(fi.Name)); // filename
dataToSend.AddRange(fileData); // file binary data
using (TcpClient client = new TcpClient())
{
client.Connect(Settings.IpAddress, Settings.Port + 1);
// Get a client stream for reading and writing.
using (NetworkStream stream = client.GetStream())
{
// server is ready
stream.Write(dataToSend.ToArray(), 0, dataToSend.ToArray().Length);
}
}
}
catch (ArgumentNullException e)
{
Debug.WriteLine(e);
}
catch (SocketException e)
{
Debug.WriteLine(e);
}
}
}
Em seguida, no lado do servidor fique da seguinte maneira:
private void Listen()
{
TcpListener server = null;
try
{
// Setup the TcpListener
Int32 port = Settings.Port + 1;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[1024];
List<byte> data;
// Enter the listening loop.
while (true)
{
Debug.WriteLine("Waiting for a connection... ");
string filePath = string.Empty;
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
using (TcpClient client = server.AcceptTcpClient())
{
Debug.WriteLine("Connected to client!");
data = new List<byte>();
// Get a stream object for reading and writing
using (NetworkStream stream = client.GetStream())
{
// Loop to receive all the data sent by the client.
while ((stream.Read(bytes, 0, bytes.Length)) != 0)
{
data.AddRange(bytes);
}
}
}
int fileNameLength = BitConverter.ToInt32(data.ToArray(), 0);
filePath = Encoding.Unicode.GetString(data.ToArray(), 4, fileNameLength);
var binary = data.GetRange(4 + fileNameLength, data.Count - 4 - fileNameLength);
Debug.WriteLine("File successfully downloaded!");
// write it to disk
using (BinaryWriter writer = new BinaryWriter(File.Open(filePath, FileMode.Append)))
{
writer.Write(binary.ToArray(), 0, binary.Count);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
alguém pode ver algo que eu estou ausente / fazendo de errado?
Solução
A corrupção é causada pelo código seguinte no servidor:
// Loop to receive all the data sent by the client.
while ((stream.Read(bytes, 0, bytes.Length)) != 0)
{
data.AddRange(bytes);
}
stream.Read
não vai sempre preencher o buffer bytes
. Não vai ser preenchido se o soquete TCP tem disponível há mais dados, ou ao ler o último pedaço da mensagem (a menos que seja um múltiplo exato do tamanho do buffer).
A chamada data.AddRange
adiciona tudo, desde bytes
(fazendo a suposição de que ele está sempre cheio). Como resultado, este irá ocasionalmente acabar adicionando dados da chamada anterior para stream.Read
. Para corrigir isso, você precisa para armazenar o número de bytes retornados por Read
e adicionar apenas esse número de bytes:
int length;
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var copy = new byte[length];
Array.Copy(bytes, 0, copy, 0, length);
data.AddRange(copy);
}
Note que você pode querer reestruturar seu código para melhorar o desempenho e uso de memória (e, provavelmente, torná-lo mais fácil de ler, como resultado). Em vez de ler todos os dados na memória no cliente antes de enviar você pode apenas escrever diretamente para o NetworkStream
. No servidor, você não precisa copiar tudo do fluxo na memória. Você pode ler fora o comprimento do nome de arquivo de 4 bytes e decodificá-lo, em seguida, ler e descodificar o nome do arquivo e, finalmente, copiar o restante do fluxo diretamente para um FileStream
(a BinaryWriter
é desnecessário).
É importante notar também que você está criando o arquivo de saída com FileMode.Append
. Isto significa que cada arquivo enviado será anexado à cópia anterior do mesmo nome. Você pode querer usar FileMode.Create
vez, que irá substituir se o arquivo já existe.