i am developing application which send and receive data between two computers but there is problem which i am facing when i send data the file size would be 4.56 kb but when i receive data on other side the file size reduce to 1.42 kb and data write in file also in complete my receiving byte size is 1024 * 5000.i am using c#.i am using TCP
here is my code
i am first sending data to tell other computer what file i want to receive
private void GetLoginFile()
{
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
char[] delimiter = splitter.ToCharArray();
byte[] fileName = Encoding.UTF8.GetBytes(myIP + "_GetLoginFile"); //file name
byte[] fileData;
fileData = Encoding.UTF8.GetBytes("null");
//byte[] fileData = reads.ReadToEnd().to; //file
byte[] fileNameLen = BitConverter.GetBytes(fileName.Length); //lenght of file name
clientData = new byte[4 + fileName.Length + fileData.Length];
fileNameLen.CopyTo(clientData, 0);
fileName.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileName.Length);
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(serverIP);
IPEndPoint ipEnd = new IPEndPoint(ipAdd, 9050);
clientSock.Connect(ipEnd); //target machine's ip address and the port number
clientSock.Send(clientData);
byte[] clientData1 = new byte[1024 * 5000];
string receivedPath = mypath + "XML\\";
int receivedBytesLen = clientSock.Receive(clientData1);
int fileNameLen1 = BitConverter.ToInt32(clientData1, 0);
string fileName1 = Encoding.ASCII.GetString(clientData1, 4, fileNameLen1);
//string file = Encoding.UTF8.GetString();
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName1, FileMode.Append));
bWrite.Write(clientData1, 4 + fileNameLen1, receivedBytesLen - 4 - fileNameLen1);
开发者_Python百科 //clientSock.Shutdown(SocketShutdown.Send);
bWrite.Close();
clientSock.Close();
}
catch (Exception ex)
{
clientSock.Close();
MessageBox.Show(ex.Message);
}
}
can anyone help me out to solve this problem.
Well, you haven't given any code... but I suspect it's your receiving code which is wrong.
You should be looping round, reading until a Read
call on the stream returns 0. Don't assume you'll get all the data in one call.
EDIT: Yup, look at your receiving code:
int receivedBytesLen = clientSock.Receive(clientData1);
What makes you think you've received all the data you need in that one call? You need to loop round, receiving until either the other end closes the connection, or you've read all the data you need.
Are you using UDP sockets? If so, then everything is fine: udp is not reliable. Use TCP to get every single byte sent.
精彩评论