我正在開發在兩臺計算機之間發送和接收數據的應用程序,但是當我發送數據文件大小爲4.56 kb時存在問題,但是當我在另一側接收數據時文件大小減少1.42 kb和數據寫入文件也完成了我的接收字節大小爲1024 * 5000.i正在使用C#。我是使用TCP丟失字節Socket編程
這裏是我的代碼
我正在第一發送數據告訴其他計算機我想要收到什麼文件
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);
//clientSock.Shutdown(SocketShutdown.Send);
bWrite.Close();
clientSock.Close();
}
catch (Exception ex)
{
clientSock.Close();
MessageBox.Show(ex.Message);
}
}
任何人都可以幫我解決這個問題。
請提供一些代碼和一些更多的細節? – 2010-07-30 14:54:44