TCP IP Android Client (phone) and PC server in c# - c#

I want to send large file from my phone to PC server which is written in c#, The code is below,
Client side;
File sdFile=new File(mRcordFilePath);
byte[] mybytearray = new byte[(int) sdFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(sdFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
OutputStream os;
try {
os = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
String name=sdFile.getName();
dos.writeUTF(name);
dos.writeLong(mybytearray.length);
int read;
while((read = dis.read(mybytearray)) != -1) {
dos.write(mybytearray, 0, read);
}
Toast.makeText(getApplicationContext(),
"Veri Gönderildi !", Toast.LENGTH_SHORT).show();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Server side;
part of server;
int fileNameLen = 1;
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
if (flag == 0)
{
fileNameLen = BitConverter.ToInt32(state.buffer, 0);
string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
receivedPath = #"C:\Users\Hankishan\Desktop\kayıtlar\" + fileName;
flag++;
}
if (flag >= 1)
{
BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
if (flag == 1)
{
writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
flag++;
}
else
writer.Write(state.buffer, 0, bytesRead);
writer.Close();
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
else
{
Invoke(new MyDelegate(LabelWriter));
}
İf I run this code,
while receiving the file (for instance 123.wav) there is an error in this row;
string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
if I change the code as;
fileNameLen = state.buffer[1];
string fileName = Encoding.UTF8.GetString(state.buffer, 2, fileNameLen);
is ok. But in this time received file is corrupted, is not played in PC,
what can I do? What is the problem?

I solved the problem. The code is here;
public void ReadCallback (IAsyncResult ar)
{
int fileNameLen = 1;
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
if (flag == 0)
{
fileNameLen = state.buffer[1];
//fileNameLen = BitConverter.ToInt32(state.buffer, 0);
string fileName = Encoding.UTF8.GetString(state.buffer, 2, fileNameLen);
receivedPath = #"C:\Users\Hankishan\Desktop\kayitlar\" + fileName;
flag++;
}
if (flag >= 1)
{
BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
if (flag == 1)
{
writer.Write(state.buffer, 2 + fileNameLen, bytesRead - (2 + fileNameLen));
flag++;
}
else
{
if (flag == 2)
{
for (int i = 0; i < state.buffer.Length; i++)
{
if (i + 8 == 1023)
break;
state.buffer[i] = state.buffer[i + 8];
}
writer.Write(state.buffer, 0, bytesRead);
flag++;
}else
writer.Write(state.buffer, 0, bytesRead);
}
writer.Close();
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
else
{
Invoke(new MyDelegate(LabelWriter));
}
}

Related

tcp/ip recieve bytes and convert to texture

I have a small problem with this. I have another program / software which converts image to bytes and sends them on. So what I need to do now is catch those bytes in Unity and convert them back to image and set that as a texture.
I've already established the connection to the other software via TCP/IP system, connection is working, other software is sending data, but I've got no idea how to convert those bytes to img.
Debug.Log("client message received as: " + clientMessage);
is just a test so I can see that data is coming through.
Here is my code
img.LoadRawTextureData(Loader);
img.Apply();
GameObject.Find("Plane").GetComponent<Renderer>().material.mainTexture = img;
//
private void ListenForIncommingRequests()
{
try
{
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 35800);
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] bytes = new Byte[1024];
while (true)
{
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var incommingData = new byte[length];
Array.Copy(bytes, 0, incommingData, 0, length);
Loader = incommingData;
string clientMessage = Encoding.ASCII.GetString(incommingData);
Debug.Log("client message received as: " + clientMessage);
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
}
Have you tried passing the bytes into LoadRawTextureData?
private byte[] ListenForIncommingRequests()
{
try
{
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 35800);
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] bytes = new Byte[1024];
while (true)
{
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var incommingData = new byte[length];
Array.Copy(bytes, 0, incommingData, 0, length);
Loader = incommingData;
string clientMessage = Encoding.ASCII.GetString(incommingData);
Debug.Log("client message received as: " + clientMessage);
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
return bytes;
}
And call it like this.
var result = ListenForIncommingRequests();
img.LoadRawTextureData(result);
img.Apply();
GameObject.Find("Plane").GetComponent<Renderer>().material.mainTexture = img;

Character Limit in filepath C#

I have the following piece of code which uploads a file and checks its validity.
First issue:
if (RadUpload1.UploadedFiles.Count == 0)
{
Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
ErrorsList.ERR_P_DATE_FILE_VALID);
}
else
{
if (RadUpload1.UploadedFiles.Count > 0)
{
foreach (UploadedFile validFile in RadUpload1.UploadedFiles)
{
FileInfo fi = new FileInfo(validFile.FileName);
Stream fs = validFile.InputStream;
IDbContextualRecord pFile = statusContext.CreateAndAddRecordForInsert(PartStoredFile.t_name);
pFile[PartStoredFile.c_partId] = _part[Part.c_id];
string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] +
"\\partRec\\" + _part[Part.c_id] + "\\" + pFile[PartStoredFile.c_id];
long bytesOnTheStream = 0L;
try
{
DirectoryInfo dir = new DirectoryInfo(targetFolder);
if (dir.Exists == false)
dir.Create();
string fullFileName = Path.Combine(targetFolder, fi.Name);
Stream targetStream = File.OpenWrite(fullFileName);
byte[] buffer = new Byte[AppConstants.BUFF_SIZE];
int bytesRead;
// while the read method returns bytes
// keep writing them to the output stream
while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0)
{
targetStream.Write(buffer, 0, bytesRead);
bytesOnTheStream += bytesRead;
}
fs.Close();
targetStream.Close();
}
catch (Exception ex)
{
throw ex;
}
What I want to do is to check if the number of characters in the filepath name exceeds 260 to display me a message of error.
This is the second issue after the modification was made:
if (RadUpload1.UploadedFiles.Count <= 0)
{
Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
ErrorsList.ERR_P_DATE_FILE_VALID);
}
else
{
if (RadUpload1.UploadedFiles.Count > 0 )
{
foreach (UploadedFile validFile in RadUpload1.UploadedFiles)
{
pomDoc = (IDbContextualRecord)Session[AppConstants.POM_DOCUMENT_NEW];
FileInfo fi = new FileInfo(validFile.FileName);
Stream fs = validFile.InputStream;
IDbContextualRecord pomFile = pomContext.CreateAndAddRecordForInsert(PomFile.t_name);
pomFile[PomFile.c_pomDocumentId] = pomDoc[PomDocument.c_id];
string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] + "\\POM\\" + pomDoc[PomDocument.c_id] + "\\" + pomFile[PomFile.c_id];
long bytesOnTheStream = 0L;
try
{
DirectoryInfo dir = new DirectoryInfo(targetFolder);
if (dir.Exists == false)
dir.Create();
string fullFileName = Path.Combine(targetFolder, fi.Name);
if (fullFileName.Length > 260)
{
throw new Exception(string.Format("The filename is too long!",fullFileName));
}
Stream targetStream = File.OpenWrite(fullFileName);
byte[] buffer = new Byte[AppConstants.BUFF_SIZE];
int bytesRead;
// while the read method returns bytes
// keep writing them to the output stream
while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0)
{
targetStream.Write(buffer, 0, bytesRead);
bytesOnTheStream += bytesRead;
}
fs.Close();
targetStream.Close();
}
catch (Exception ex)
{
throw ;
}
You just have to compare fullFileName.Lenght to 260 and raise an exception if needed:
if (RadUpload1.UploadedFiles.Count <= 0) // Changed the condition to remove the check within the else block
{
Session[AppConstants.ERROR_MESSAGE] = ErrorsList.GetErrorMessage(
ErrorsList.ERR_P_DATE_FILE_VALID);
}
else
{
foreach (UploadedFile validFile in RadUpload1.UploadedFiles)
{
FileInfo fi = new FileInfo(validFile.FileName);
Stream fs = validFile.InputStream;
IDbContextualRecord pFile = statusContext.CreateAndAddRecordForInsert(PartStoredFile.t_name);
pFile[PartStoredFile.c_partId] = _part[Part.c_id];
string targetFolder = AppSession.Current.ConfigParameters[AppConstants.UPLOAD_FILE_PATH] +
"\\partRec\\" + _part[Part.c_id] + "\\" + pFile[PartStoredFile.c_id];
long bytesOnTheStream = 0L;
try
{
DirectoryInfo dir = new DirectoryInfo(targetFolder);
if (dir.Exists == false)
dir.Create();
string fullFileName = Path.Combine(targetFolder, fi.Name);
if(fullFileName.Length > 260)
{
throw new Exception(string.Format("The filename {0} is too long.", fullFileName));
// Or do whatever you want
}
Stream targetStream = File.OpenWrite(fullFileName);
byte[] buffer = new Byte[AppConstants.BUFF_SIZE];
int bytesRead;
// while the read method returns bytes
// keep writing them to the output stream
while ((bytesRead = fs.Read(buffer, 0, AppConstants.BUFF_SIZE)) > 0)
{
targetStream.Write(buffer, 0, bytesRead);
bytesOnTheStream += bytesRead;
}
fs.Close();
targetStream.Close();
}
catch (Exception ex)
{
throw;
}
Also, you don't want to throw ex; but rather throw; or this will reset the stacktrace, see Is there a difference between "throw" and "throw ex"?

When calculating to report backgroundworker progressBar i'm getting exception cant divide by zero what is wrong?

This is the method:
Getting the Length of the files give 0 already.
public void DownloadFtpContent(object sender ,string file, string filesdirectories,string fn)
{
try
{
BackgroundWorker bw = sender as BackgroundWorker;
string filenameonly = Path.GetFileName(file);
string ftpdirectories = Path.Combine(ftpcontentdir, filesdirectories);
string fileurl = "ftp://" + file;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(fileurl);
reqFTP.Credentials = new NetworkCredential(UserName, Password);
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.KeepAlive = true;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.Proxy = null;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
if (!Directory.Exists(ftpdirectories))
{
Directory.CreateDirectory(ftpdirectories);
}
FileStream writeStream = new FileStream(ftpdirectories + "\\" + filenameonly, FileMode.Create);
string fnn = ftpdirectories + "\\" + filenameonly;
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
long FileSize = new FileInfo(fnn).Length;
string FileSizeDescription = GetFileSize(FileSize);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(bytesRead), FileSizeDescription);
bw.ReportProgress((int)(((decimal)bytesRead / (decimal)FileSize) * 100), SummaryText);
}
writeStream.Close();
response.Close();
}
catch (WebException wEx)
{
//MessageBox.Show(wEx.Message, "Download Error");
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "Download Error");
}
}
}
Already on this line the result is 0:
long FileSize = new FileInfo(fnn).Length;
In fnn i have: c:\myftpdownloads\root\Images\CB 967x330.jpg
Why the result of the Length is 0 ?
And the file is not 0kb size.
EDIT
This is how i'm calling the download method from backgroundworker dowork event:
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < numberOfFiles.Count; i++)
{
int fn = numberOfFiles[i].IndexOf(txtHost.Text, 0);
string fn1 = numberOfFiles[i].Substring(txtHost.Text.Length + 1, numberOfFiles[i].Length - (txtHost.Text.Length + 1));
string dirs = Path.GetDirectoryName(fn1);
string filename = Path.GetFileName(fn1);
ftpProgress1.DownloadFtpContent(sender,numberOfFiles[i], dirs, filename);
}
}
In fnn i have: c:\myftpdownloads\root\Images\CB 967x330.jpg Why the result of the Length is 0 ?
It doesn't really matter why the result of the length is 0. It does matter that you divide that number by 0 without any protection.
Just check before you divide:
if( FileSize != 0 ){...}

TCP Asynchronous socket slow on receiving server?

So my problem is the my server cannot receive all the data the client is sending , which is causing virtually no packets to be getting received at all on server side.
Basically the problem is I need to quite heavily sleep the CLientLoop , in order for the sent data to be received. as in Thread.Sleep(1000)
(This is been tested locally)
My server code is here :
public void RecieveAsync()
{
socket.BeginReceive(lenBuffer, 0, lenBuffer.Length, SocketFlags.None,recieveCallBack, null);
}
private void recieveCallBack(IAsyncResult ar)
{
int rec = socket.EndReceive(ar);
if (rec == 0)
{
if (Disconnected != null)
{
Disconnected(this);
return;
}
if (rec != 4)
{
throw new Exception();
}
}
/
buffer = new ReceiveBuffer(BitConverter.ToInt32(lenBuffer, 0));
Also my buffer class for those interested (Might help)
\ public struct ReceiveBuffer
{
public const int BUFFER_SIZE = 1024;
public byte[] Buffer;
public int ToReceive;
public MemoryStream BufStream;
public ReceiveBuffer(int toRec)
{
Buffer = new byte[BUFFER_SIZE];
ToReceive = toRec;
BufStream = new MemoryStream(toRec);
}
public void Dispose()
{
Buffer = null;
ToReceive = 0;
Close();
if (BufStream != null) BufStream.Dispose();
}
public void Close()
{
if (BufStream != null && BufStream.CanWrite)
{
BufStream.Close();
}
}
So my client is sending the data in this method
public void Send(byte[] data, int index, int length)
{
//add data as state
socket.BeginSend(BitConverter.GetBytes(length), 0, 4, SocketFlags.None, new AsyncCallback(sendCallback), data);
socket.BeginSend(data, index, length, SocketFlags.None, new AsyncCallback(sendCallback), null);
}
Where the information being sent is here
public void ClientLoop()
{
try{
Console.WriteLine("In Client loop");
client.DataRecieved +=new Client.DataRecievedEventHandler(Client_DataRecieved);
while (true)
{
byte[] playerData = PreparePlayerData();
client.Send(playerData, 0, playerData.Length);
//client.RecieveAsync();
Thread.Sleep(10);
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.ToString());
}
}
with
public byte[] PreparePlayerData()
{
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write((int)Commands.Text);
string data = "";
string Position = Math.Round(MultiplayerScreen.localPlayer.Position.X, 2).ToString() + "|" + Math.Round(MultiplayerScreen.localPlayer.Position.Y, 2).ToString();
string effects = (MultiplayerScreen.localPlayer.Effects == Microsoft.Xna.Framework.Graphics.SpriteEffects.None) ? "0" : "1";
string animaton = (MultiplayerScreen.localPlayer.Animation.MoveState).ToString();
string frame = MultiplayerScreen.localPlayer.Animation.XFrame.ToString();
data = "P|" + Position + "|" + effects + "|" + animaton + "|" + frame;
bw.Write(data);
bw.Close();
byte[] toSend = ((MemoryStream)bw.BaseStream).ToArray();
bw.BaseStream.Dispose();
return toSend;
}
Also this is the method where the server processes the data received
void Client_DataRecieved(Client sender, ReceiveBuffer e)
{
BinaryReader r = new BinaryReader(e.BufStream);
Commands header = (Commands)r.ReadInt32();
string s = r.ReadString();
Console.WriteLine("Client has received " + s);
switch (header)
{
case Commands.Player:
{
HandlePlayerData(s);
Console.WriteLine("The player data has been updated");
}
break;
case Commands.Text:
{
if (s.StartsWith("clientAccepted"))
{
connectedPlayer.isOnline = true;
}
if (s.StartsWith("P|"))
{
s = s.Remove(0, 2);
HandlePlayerData(s);
}
}
break;
}
}
socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, receivePacketCallback, null);
}
void receivePacketCallback(IAsyncResult ar)
{
int rec = socket.EndReceive(ar);
if (rec <= 0)
{
return;
}
buffer.BufStream.Write(buffer.Buffer, 0, rec);
buffer.ToReceive -= rec;
if (buffer.ToReceive > 0)
{
Array.Clear(buffer.Buffer, 0, buffer.Buffer.Length);
socket.BeginReceive(buffer.Buffer, 0, buffer.Buffer.Length, SocketFlags.None, receivePacketCallback, null);
return;
}
if (DataRecieved != null)
{
buffer.BufStream.Position = 0;
DataRecieved(this, buffer);
}
buffer.Dispose();
}

Socket.Receive() returns incorrect amount of data

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.

Categories

Resources