[英]data received different from data sent through a c sharp socket
我正在嘗試將文件從客戶端發送到服務器,因此我將文件加載到客戶端的字節數組中,並通過 send() 方法將其發送到服務器,但接收到的數組不同且更大比發送的數組,我想知道這是否是協議問題(但我使用的是 tcp 協議來確保錯誤檢測):
客戶端代碼:
IPAddress ipAddress = new IPAddress(ip);
IPEndPoint ipEnd = new IPEndPoint(ipAddress, 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
FileStream fl = File.Open("pos.xls",FileMode.Open);
byte[] fileData = ReadFully(fl);
fl.Close();
byte[] clientData = new byte[ fileData.Length];
fileData.CopyTo(clientData,0);
curMsg = "Connection to server ...";
clientSock.Connect(ipEnd);
curMsg = "File sending...";
clientSock.Send(clientData);
curMsg = "Disconnecting...";
clientSock.Close();
curMsg = "File transferred.";
服務器代碼:
curMsg = "Starting...";
sock.Listen(100);
curMsg = "Running and waiting to receive file.";
byte[] clientData = new byte[1024 * 5000];
while (true)
{
Socket clientSock = sock.Accept();
clientData = new byte[1024 * 5000];
int receivedBytesLen = clientSock.Receive(clientData);
curMsg = "Receiving data...";
FileStream fz = writeFully(clientData);
fz.Close();
curMsg = "Saving file...";
您已經定義clientData = new byte[1024 * 5000];
- 然后你不要使用receivedBytesLen
。 我不記得Receive
重載是否會在 EOF 之前讀取盡可能多的內容,或者只是“一些或 EOF”(后者是Stream.Read
行為),但您必須驗證並使用receivedBytesLen
。
IMO,固定緩沖區的方法本質上是有缺陷的,因為它也不能很好地處理過大的輸入。 我個人會在這里使用NetworkStream
; 那么你的整個代碼變成:
using(var fz = File.Create(path)) {
networkStream.CopyTo(fz);
}
這里另一種常見的方法是將預期大小作為數據的前綴發送; 這樣您就可以驗證您是否擁有所需的數據。 我個人不會使用此信息在 memory 中創建正確大小的緩沖區,因為這仍然不允許使用史詩大小的文件(但是, Stream
可以)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.