public void SendFile(string remoteHostIP, int remoteHostPort, string longFileName, string shortFileName)
{
byte[] fileNameByte = Encoding.ASCII.GetBytes(shortFileName);
byte[] fileData = File.ReadAllBytes(longFileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
TcpClient clientSocket = new TcpClient(remoteHostIP, remoteHostPort);
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Write(clientData, 0, clientData.GetLength(0));
networkStream.Close();
}
It is possible to use this function to send a 1GB file because the maximum file size i had been try to send now is only up to 400MB. More than that is will cause an error of 'System.OutOfMemoryException'.
When i use another method to split the file into few parts but the server side can't receive the parts continuously and can only receive one of the part.
private void splitBigFile(string FileInputPath, byte[] inputArray)
{
int port = 1113;
double partSize = 104852000;
int partSize2 = 104852000;
string FolderOutputPath = "C:\\Users\\xx\\Desktop\\testing split";
string currPartPath;
string shortNameSplit;
FileStream fileStream = new FileStream(FileInputPath, FileMode.Open);
FileInfo fiSource = new FileInfo(txtFile.Text);
double sourceLength = fiSource.Length;
partNum = (int)Math.Ceiling((double)(sourceLength / partSize));
for (int i = 0; i < partNum; i++)
{
if (i == (partNum - 1))
{
partSize2 = (int)fiSource.Length - (i * 104852000);
}
currPartPath = FolderOutputPath + "\\" + fiSource.Name + "." + String.Format(#"{0:D4}", i) + ".part";
shortNameSplit = fiSource.Name + "." + String.Format(#"{0:D4}", i) + ".part";
byte[] fileNameByte = Encoding.ASCII.GetBytes(shortNameSplit);
byte[] readStream = new byte[partSize2];
byte[] concateFile = new byte[5 + fileNameByte.Length];
int ipSend = ((partNum - 1 - i) << 1);
ipSend |= 0; // for differentiate ip or file
byte[] byteSend = new byte[1];
byteSend[0] = (byte)ipSend;
fileStream.Read(readStream, 0, partSize2);
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
byteSend.CopyTo(concateFile, 0);
fileNameLen.CopyTo(concateFile, 1);
fileNameByte.CopyTo(concateFile, 5);
concateFile.CopyTo(inputArray, 0);
readStream.CopyTo(inputArray, concateFile.Length);
string ipAddress = "192.168.43.67";
int sendport = 1113;
//Task.Factory.StartNew(() => SendBigFileSize(ipAddress, sendport, inputArray[i]));
Array.Clear(readStream, 0, readStream.Length);
Array.Clear(fileNameLen, 0, fileNameLen.Length);
Array.Clear(fileNameByte, 0, fileNameByte.Length);
Array.Clear(byteSend, 0, byteSend.Length);
Array.Clear(byteSend, 0, byteSend.Length);
}
fileStream.Close();
}
Of course, just not all at once. Send chunks at a time.
Besides, the maximum TCP packet size is 64k, and the MTU is 1500 bytes. Your huge buffer is getting split up too, but you're using up a lot of memory doing it. Instead read 32MB (safe HDD I/O buffer size) at a time from your file and send it, then read the next bit.
Related
I've some code, to send file data using TcpClient, but it's too slow.
Send sample data of 10 bytes, the data is sent and receive as expected.
Send file with just a few MB takes long time
public static void SendBytes(TcpClient clientSocket, byte[] outStream)
{
Debug.WriteLine("SendBytes() number of bytes: " + outStream.Length.ToString());
byte[] encoded_outStream = EncoderDecoder.Encoder(outStream);
NetworkStream serverStream = clientSocket.GetStream();
byte[] rv = new byte[encoded_outStream.Length + ProgramState.end_networkdata_bytes.Length];
System.Buffer.BlockCopy(encoded_outStream, 0, rv, 0, encoded_outStream.Length);
System.Buffer.BlockCopy(ProgramState.end_networkdata_bytes, 0, rv, encoded_outStream.Length, ProgramState.end_networkdata_bytes.Length);
serverStream.Write(rv, 0, rv.Length);
serverStream.Flush();
}
private static int MAX_SIZE = 500000000;
public static byte[] ReceiveBytes(TcpClient clientSocket)
{
Debug.WriteLine("[" + DateTime.Now.ToString("G") + "] - " + "ReceiveBytes() started.");
clientSocket.NoDelay = true;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[MAX_SIZE];
clientSocket.ReceiveBufferSize = MAX_SIZE;
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
int index = GetFirstOccurance(ProgramState.end_networkdata_bytes[0], bytesFrom);
Debug.WriteLine("ReceiveBytes(), SubArray index: " + index.ToString());
byte[] tmp_res = bytesFrom.SubArray(0, index);
byte[] res = EncoderDecoder.Decoder(tmp_res);
Debug.WriteLine("ReceiveBytes() number of bytes: " + res.Length.ToString());
return res;
}
EDIT: The code for receiving data in multiple chunks
private static int MAX_SIZE = 10000;
public static byte[] ReceiveBytes(TcpClient clientSocket)
{
Debug.WriteLine("[" + DateTime.Now.ToString("G") + "] - " + "ReceiveBytes() started.");
clientSocket.NoDelay = true;
NetworkStream networkStream = clientSocket.GetStream();
clientSocket.ReceiveBufferSize = MAX_SIZE;
byte[] tmp_bytesFrom = new byte[MAX_SIZE];
while(GetFirstOccurance(ProgramState.end_networkdata_bytes[0], tmp_bytesFrom) < 0)
{
networkStream.Read(tmp_bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
}
Debug.WriteLine("[" + DateTime.Now.ToString("G") + "] - " + "ReceiveBytes(), received number of raw bytes: " + tmp_bytesFrom.Length.ToString());
return tmp_bytesFrom;
}
On sending file with few MB (7.5 MB), the ReceiveBytes() function take: ~9 minutes.
Note:
1. The Encoder() and Decoder() function does not affect my speed.
2. Reduce the buffer size does not make receiving faster. (tested).
Well, I'm trying to convert a large information in bytes for string. (11076 length)
The problem in the end, the information is with missing characters. (length 10996)
Look:
The information is received by Winsock connection, look the proccess:
public static void UpdateClient(UserConnection client)
{
string data = null;
Decoder utf8Decoder = Encoding.UTF8.GetDecoder();
Console.WriteLine("Iniciando");
byte[] buffer = ReadFully(client.TCPClient.GetStream(), 0);
int charCount = utf8Decoder.GetCharCount(buffer, 0, buffer.Length);
Char[] chars = new Char[charCount];
int charsDecodedCount = utf8Decoder.GetChars(buffer, 0, buffer.Length, chars, 0);
foreach (Char c in chars)
{
data = data + String.Format("{0}", c);
}
int buffersize = buffer.Length;
Console.WriteLine("Chars is: " + chars.Length);
Console.WriteLine("Data is: " + data);
Console.WriteLine("Byte is: " + buffer.Length);
Console.WriteLine("Size is: " + data.Length);
Server.Network.ReceiveData.SelectPacket(client.Index, data);
}
public static byte[] ReadFully(Stream stream, int initialLength)
{
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
chunk = stream.Read(buffer, read, buffer.Length - read);
checkreach:
read += chunk;
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte == -1)
{
return buffer;
}
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
goto checkreach;
}
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
Anyone have tips or a solution?
It's perfectly normal for UTF-8 encoded text to be more bytes than the number of characters. In UTF-8 some characters (for example á and ã) are encoded into two or more bytes.
As the ReadFully method returns garbage if you try to use it to read more than fits in the initial buffer or if it can't read the entire stream with one Read call, you shouldn't use it. Also the way that the char array is converted to a string is extremely slow. Just use a StreamReader to read the stream and decode it to a string:
public static void UpdateClient(UserConnection client) {
string data;
using (StreamReader reader = new StreamReader(client.TCPClient.GetStream(), Encoding.UTF8)) {
data = reader.ReadToEnd();
}
Console.WriteLine("Data is: " + data);
Console.WriteLine("Size is: " + data.Length);
Server.Network.ReceiveData.SelectPacket(client.Index, data);
}
I have a problem with tcpclient, I need to send one or more files, so I have an application with server and client, the protocol is this :
1) I send some strings with information about number of files, files name and their sizes, all this with streamwriter.writeline (received from server with the function
streamreader.readline)
2) After these strings I send the files, after each file the server answers to the client with a streamwriter.writeline of "ACK". The file is sent with the
networkstream.write method, and received with networkstream.read.
The problem is that the server reads till the received bytes are equal to the file size, but... despite the client "seems" to send every byte of the file, the server
receives fewer bytes in total! So the application is blocked in this step, the server is waiting for the next bytes and the client is waiting for the string of "ACK"
with the streamreader.readline before to send the next file or just to finish the operation.
I also wanted to check what the server receives, so I print the number of bytes received during the reading cycle , discovering that sometimes the server reads fewer bytes than the buffer size of the stream (fixed to 1024). This should be normal because TCP reads as soon as it can, it should not be the real problem, right? I can't
believe that tcp loses bytes, but I don't know how to resolve.
Here you can find some part of codes :
----SERVER SIDE----------
..........Doing Stuffs.............
//secServer is the TCPListener socket.
this.secSHandler = secServer.AcceptTcpClient();
this.secSHandler.ReceiveBufferSize = 1024;
this.secSHandler.SendBufferSize = 1024;
this.is_connected_now = true;
print("is connected!!! ");
//Taking streams...
this.stream = this.secSHandler.GetStream();
this.sr = new StreamReader(stream);
this.sw = new StreamWriter(stream);
string first = sr.ReadLine();
print("I read + " + first + " .");
int numFiles = 0;
string connType = first.Substring(0, 6);
if (connType.CompareTo("CLIENT") == 0)
{
//SINCR CLIENT -> SERVER
string clipType = first.Substring(7, 4);
if (clipType.CompareTo("FILE") == 0)
{
//CASE RECEIVE FILE
int posSeparator = first.IndexOf('*');
string nFiles = first.Substring(12, first.Length - 13);
numFiles = Convert.ToInt16(nFiles);
string[] fileNames = new string[numFiles];
int[] fileSizes = new int[numFiles];
//TAKE FROM THE CLIENT ALL FILE NAMES AND SIZES
for (int i = 0; i < numFiles; i++)
{
fileNames[i] = sr.ReadLine();
print("Name file : I read " + fileNames[i]);
string dim = sr.ReadLine();
fileSizes[i] = Convert.ToInt32(dim);
print("Size file : I read " + fileSizes[i]);
}
//RECEVING FILES
for (int i = 0; i < numFiles; i++)
{
receive_single_file_1(stream, fileSizes[i], fileNames[i]); //CANNOT GO AFTER THIS POINT
sw.WriteLine("File sent - number " + i);
sw.Flush();
}
}
}
.............Doing others stuffs.............
sr.Close();
sw.Close();
THE FUNCTION RECEIVE SINGLE FILE IS HERE BELOW
public bool receive_single_file_1(NetworkStream netstream, int size, string filename)
{
int sizeToRead = 0;
string f_name = "";
//...f_name is the result of another operation, for the sake of the example i write only the final instruction
f_name = filename;
byte[] RecData = new byte[1024];
int RecBytes = 0;
try
{
int totalrecbytes = 0;
FileStream Fs = new FileStream((tempFold + f_name), FileMode.OpenOrCreate, FileAccess.Write);
//COUNTER OF THE WHILE
int nciclo = 0;
while ((RecBytes = netstream.Read(RecData, 0, 1024)) > 0)
{
//I defined print in another context...
totalrecbytes += RecBytes;
if(RecBytes!=1024)
print("Cycle : "+ nciclo +" Content RecBytes : " + RecBytes + " e RecData.Length : " + RecData.Length + " byte reads : " + totalrecbytes + ".");
Fs.Write(RecData, 0, RecBytes);
if (totalrecbytes >= size)
{
print("Read all bytes " + totalrecbytes + " over " + size + " .");
break;
}
//Refresh the buffer
RecData = new byte[1024];
nciclo++;
}
print("End of transfer. Received " + totalrecbytes + "File :" + filename + " Saved on " + tempFold);
Fs.Close();
}
catch (Exception ex)
{
//Ok here i return false, but i do some other stuff before
return false;
}
return true;
}
----END OF SERVER SIDE--------------
--------CLIENT SIDE--------------
.....DOING STUFFS....
//sw is the streamWriter, Sr the streamReader and the stream is the networkstream
System.Collections.Specialized.StringCollection formats = Clipboard.GetFileDropList();
sw.WriteLine("CLIENT:FILE:" + formats.Count + "*");
sw.Flush();
//Sending to the server filename and relative size
foreach (string filename in formats)
{
//Ok the * has sense in my protocol...ignore it.
sw.WriteLine((Directory.Exists(filename)) ? System.IO.Path.GetFileName(filename) + "*" : System.IO.Path.GetFileName(filename));
sw.Flush();
FileStream Fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
sw.WriteLine(Fs.Length);
sw.Flush();
stream.Flush();
Fs.Close();
}
//Sending files
foreach (string filename in formats)
{
//client_sync is the class that wrap the TcpClient socket
client_sync.send_single_file(stream, filename);
resp = sr.ReadLine();
}
....DOING STUFF AND end of this function...
The send file function is defined in this way :
(note : i take this function from code project some weeks ago)
public void send_single_file(NetworkStream netstream, string filename)
{
//connected is a param of my class
if (!connected) return;
byte[] SendingBuffer = null;
try
{
FileStream Fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
int NoOfPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(Fs.Length) / Convert.ToDouble(this.BufferSize)));
//NOTE: BUFFERSIZE IS 1024
int TotalLength = (int)Fs.Length, CurrentPacketLength = 0;
int bytes_send = 0;
for (int i = 0; i < NoOfPackets; i++)
{
if (TotalLength > this.BufferSize)
{
CurrentPacketLength = this.BufferSize;
TotalLength = TotalLength - CurrentPacketLength;
}
else
CurrentPacketLength = TotalLength;
SendingBuffer = new byte[CurrentPacketLength];
Fs.Read(SendingBuffer, 0, CurrentPacketLength);
netstream.Write(SendingBuffer, 0, SendingBuffer.Length);
bytes_send += CurrentPacketLength;
}
Fs.Close();
}
catch (Exception ex)
{
netstream.Close();
//my function
close_connection();
}
netstream.Flush();
}
---------END OF CLIENT SIDE------
So...someone can help me to escape from this hell??? THX :)
As school project I'm creating a FileSharing application.
I send all the messages I want to the server and everything is fine, but when it comes to Upload a file to the server, the file is never the way it should be. I debugged the application and discovered that the Socket is not returning the correct amount of bytes.
I don't know if that's the correct way it should be, but I thinks it's wrong.
For example when I upload a small .txt file, and open it with Notepad++ I see a lot of null's at the end of the file, wich means that I'm writting more then it should be written. I searched it on the internet and found an application at codeplex that does the same that I'm doing, but the socket returns the correct amount of data, http://srf.codeplex.com/.
I would appreciate if someone could help me.
Sorry if english sucks, its not my native language.
Server function that handles first message and does receives the clint connection:
public void Brodcast()
{
tcpListener.Start();
while (true)
{
try
{
ClientSocket = tcpListener.AcceptSocket();
MessageReceiving();
}
catch { }
}
}
public void MessageReceiving()
{
if (ClientSocket.Connected)
{
OpenPackage.MessageTypeToBytes RSMessage = new OpenPackage.MessageTypeToBytes();
ClientSocket.Receive(RSMessage.MessageBytes, 512, SocketFlags.None);
if (RSMessage.TypeOfMessage == MessageType.Login)
DoLogin();
else if (RSMessage.TypeOfMessage == MessageType.Download)
SendFile();
else if (RSMessage.TypeOfMessage == MessageType.Upload)
ReceiveFile();
else if (RSMessage.TypeOfMessage == MessageType.NConta)
NewAccount();
else if (RSMessage.TypeOfMessage == MessageType.Search)
SearchResult();
else if (RSMessage.TypeOfMessage == MessageType.Apagar)
DeleteFile();
}
}
Server:
public void ReceiveFile()
{
try
{
byte[] MessageBytes = new byte[512];
ClientSocket.Receive(MessageBytes, 512, SocketFlags.None);
string Nickname = Encoding.ASCII.GetString(MessageBytes);
string[] CNickFich = Nickname.Split('$');
FileHandler Handler = new FileHandler();
long DirectorySize = Handler.GetDirectorySize("C:\\" + CNickFich[0]);
long FileSize = long.Parse(CNickFich[2]);
bool Subs = false;
if ((FileSize + DirectorySize) < MaxFolderSize && MaxFileSize > FileSize)
{
if (!Directory.Exists("C:\\" + CNickFich[0]))
Directory.CreateDirectory("C:\\" + CNickFich[0]);
if (File.Exists("C:\\" + CNickFich[0] + "\\" + CNickFich[1]))
{
File.Delete("C:\\" + CNickFich[0] + "\\" + CNickFich[1]);
Subs = true;
}
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.OK };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
int qtdReceived = 0;
long CurrentSize = 0;
byte[] FileBuffer = new byte[BufferSize];
FileStream FileStr = new FileStream("C:\\" + CNickFich[0] + "\\" + CNickFich[1], FileMode.CreateNew, FileAccess.Write);
BufferedStream BufferStr = new BufferedStream(FileStr);
while (CurrentSize < FileSize)
{
qtdReceived = ClientSocket.Receive(FileBuffer, 0, FileBuffer.Length, 0);
CurrentSize += qtdReceived;
BufferStr.Write(FileBuffer, 0, qtdReceived);
BufferStr.Flush();
}
BufferStr.Close();
FileStr.Close();
SqlDataAdapter data = new SqlDataAdapter("SELECT COD_CONTA FROM CONTAS WHERE NICKNAME='"
+ CNickFich[0] + "'", OConn);
DataTable dt = new DataTable();
data.Fill(dt);
if (NFicheiro(Handler.MD5HashFromFile("C:\\" + CNickFich[0] + "\\" + CNickFich[1]), "C:\\" + CNickFich[0] + "\\" + CNickFich[1], Subs,
int.Parse(dt.Rows[0][0].ToString()), CNickFich[3]))
MessageInBytes.TypeOfMessage = MessageType.OK;
else
MessageInBytes.TypeOfMessage = MessageType.Erro;
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
//NFicheiro(new FileHandler().MD5HashFromFile("C:\\" + CNickFich[0] + "\\" + CNickFich[1]), "C:\\" + CNickFich[0], false, 1, );
}
else
{
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Erro };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
}
}
catch
{
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Erro };
ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
}
}
Client:
private void UploadWork_DoWork(object sender, DoWorkEventArgs e)
{
FileStream FileStr = null;
BufferedStream BufferStr = null;
Stopwatch Counter = new Stopwatch();
try
{
int CurrentProgress = 0;
Program.CTasks.ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Program.CTasks.ClientSocket.ReceiveTimeout = 60000;
Program.CTasks.ClientSocket.SendTimeout = 60000;
Program.CTasks.ClientSocket.Connect(IPAddress.Parse(Program.CTasks.HostName), Program.CTasks.Port);
MessageTypeToBytes MessageInBytes = new MessageTypeToBytes() { TypeOfMessage = MessageType.Upload };
Program.CTasks.ClientSocket.Send(MessageInBytes.MessageBytes, 512, SocketFlags.None);
FileInfo FileNFO = new FileInfo(Open.FileName);
byte[] NickPath = new byte[512];
byte[] UNickPath = Encoding.ASCII.GetBytes(Program.Nickname + "$" + Open.FileName.Substring(Open.FileName.LastIndexOf('\\') + 1) + "$" + FileNFO.Length.ToString() + "$");
byte[] TagCollectionBytes = Encoding.ASCII.GetBytes(TagCollection + "$");
UNickPath.CopyTo(NickPath, 0);
TagCollectionBytes.CopyTo(NickPath, UNickPath.Length);
Program.CTasks.ClientSocket.Send(NickPath, 512, SocketFlags.None);
Program.CTasks.ClientSocket.Receive(MessageInBytes.MessageBytes, 512, SocketFlags.None);
if (MessageInBytes.TypeOfMessage == MessageType.OK)
{
long FileSize = FileNFO.Length;
long CurrentFileSize = 0;
long qtdRead = 0;
byte[] FileBytes = new byte[BufferSizer];
FileStr = new FileStream(Open.FileName, FileMode.Open, FileAccess.Read);
BufferStr = new BufferedStream(FileStr);
Counter.Start();
while ((qtdRead = BufferStr.Read(FileBytes, 0, FileBytes.Length)) > 0)
{
Program.CTasks.ClientSocket.Send(FileBytes, 0, FileBytes.Length, 0);
CurrentFileSize += qtdRead;
CurrentProgress = (int)((CurrentFileSize * 100) / FileSize);
UploadSpeed = ((double)CurrentFileSize / (Counter.Elapsed.TotalMilliseconds / 100));
UploadWork.ReportProgress(CurrentProgress);
}
FileStr.Close();
Counter.Stop();
Program.CTasks.ClientSocket.Receive(MessageInBytes.MessageBytes, 512, SocketFlags.None);
Program.CTasks.ClientSocket.Close();
}
}
catch
{
try
{
Counter.Stop();
FileStr.Close();
Program.CTasks.ClientSocket.Close();
}
catch { }
}
}
You're sending too much data... at the end of the file FileBytes will on longer be completely full, and you should only send qtdRead bytes.
Replace
Program.CTasks.ClientSocket.Send(FileBytes, 0, FileBytes.Length, 0);
With
Program.CTasks.ClientSocket.Send(FileBytes, 0, qtdRead, 0);
You are using your buffer length rather than the length of what you read when sending.
I'm trying to securely transfer files between 2 devices, so I'm using an SslStream attached to a TcpClient. Documents and text files come across just fine, but image files don't show up correctly. The following is the server code:
listener = new TcpListener(IPAddress.Any, 1337);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback), new LocalCertificateSelectionCallback(CertificateSelectionCallback));
var certificate = Connection.GetClientCertificate(((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
try
{
sslStream.AuthenticateAsServer(certificate, true, SslProtocols.Default, true);
sslStream.ReadTimeout = 5000;
sslStream.WriteTimeout = 5000;
var messageData = ReadMessage(sslStream);
var mode = messageData[0];
var tokenBytes = messageData.Splice(1, 16);
var fileNameBytes = messageData.Splice(17, 128);
var fileBytes = messageData.Splice(146);
var fileName = Encoding.ASCII.GetString(fileNameBytes).TrimEnd('\0');
using (var tempFile = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
{
tempFile.Write(fileBytes, 0, fileBytes.Length);
tempFile.Flush();
}
if (mode == 0)
tempFiles.Add(fileName);
Process.Start(fileName);
}
catch (AuthenticationException e)
{
MessageBox.Show("The other side failed to authenticate.");
}
finally
{
sslStream.Close();
client.Close();
}
}
And ReadMessage is defined as follows:
private static byte[] ReadMessage(SslStream sslStream)
{
byte[] buffer = new byte[2048];
MemoryStream stream = new MemoryStream();
int bytes = -1;
while (bytes != 0)
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
stream.Write(buffer, 0, bytes);
}
return stream.ToArray();
}
And then the client code is this:
TcpClient client = new TcpClient();
client.Connect(new IPEndPoint(IPAddress.Parse(ip), 1337));
SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(CertificateValidationCallback), new LocalCertificateSelectionCallback(CertificateSelectionCallback));
var certificate = Connection.GetClientCertificate(ip);
try
{
sslStream.AuthenticateAsClient(ip, new X509CertificateCollection() { certificate }, SslProtocols.Default, false);
sslStream.ReadTimeout = 5000;
sslStream.WriteTimeout = 5000;
sslStream.Write(data);
}
catch (AuthenticationException e)
{
MessageBox.Show("The other side failed to authenticate.");
}
finally
{
sslStream.Close();
client.Close();
}
And the code that calls into it just does:
var fileBytes = File.ReadAllBytes(file);
var tokenBytes = Encoding.UTF8.GetBytes(token);
var fileNameBytes = Encoding.UTF8.GetBytes(Path.GetFileName(file));
var buffer = new byte[145 + fileBytes.Length];
buffer[0] = 1;
for (int i = 0; i < 16; i++)
{
buffer[i + 1] = tokenBytes[i];
}
for (int i = 0; i < fileNameBytes.Length; i++)
{
buffer[i + 17] = fileNameBytes[i];
}
for (int i = 0; i < fileBytes.Length; i++)
{
buffer[i + 145] = fileBytes[i];
}
SocketConnection.Send(ip, buffer);
Is there anything inherently wrong with what I'm doing, or do I need to do something different for images?
EDIT: I have changed it to reflect the current code, and also, after doing a dump of the raw bytes on both ends, it looks like for some reason the bytes are getting rearranged when they come over the wire. Is there any way to ensure that the bytes come across in the original order?
In ReadMessage you're writing bytes.Length bytes to the stream, regardless of the number of bytes that were actually read. Try:
private static byte[] ReadMessage(SslStream sslStream)
{
byte[] buffer = new byte[2048];
MemoryStream stream = new MemoryStream();
int bytes = -1;
while (bytes != 0)
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
// Use "bytes" instead of "buffer.Length" here
stream.Write(buffer, 0, bytes);
}
return stream.ToArray();
}
Based on your follow-up, you're also taking the file data from the wrong point in the buffer, and so you're losing the first byte of the file.
Your code should be:
var fileBytes = messageData.Splice(145); // File data starts at 145, not 146
Is this possibly a conflict between endianness? If the bytes from the server are ABCDEF and the client is seeing the image bytes as BADCFE then that's the issue.
I haven't worked with image files, but when I read a short or an int instead of a String from the bytes coming in over the wire, I do something like this:
int intFromStream = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(byteArrayWithLength4, 0));