我正在使用自定义的客户端服务器套接字应用程序传输文件。传输过程分为多个阶段,文件本身分为多个块(每个块为4K大小)。 所以,这就是问题所在。输入套接字缓冲区不会被新的块覆盖,而只会继续追加到现有的块中。
以下是我的部分客户代码。服务器代码很好,因为已经存在用C ++编写的客户端代码。我正在用C#重写客户端。套接字连接没有问题。 任何帮助都会很棒。提前致谢。
Socket _clientSocket = null;
bool GetFile()
{
// _strIPAddress and _nPortNumber are already assigned to valid data
IPAddress _ipAddress;
if (IPAddress.TryParse(_strIPAddress, out _ipAddress) == false)
return false;
IPEndPoint _serverEP = new IPEndPoint(_ipAddress, _nPortNumber);
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
_clientSocket.Connect(_serverEP);
// socket connected, now inform server to send the file, by sending opcode
if (SendOperationCommand() == false)
return false;
// size is received properly
if (recv_size() == false)
return false;
**// the first chunk of file data received, does not overwrite the socket buffer and thus,
// when read, it contains the previous data i.e, the file size!**
if (recv_file() == false)
return false;
return true;
}
bool SendOperationCommand()
{
...
...
// put my operation command in the buffer and send it using the following
bytesSent = _clientSocket.Send(cmd, (int)BufferSize.BUFF_SIZE_OPCODE, SocketFlags.None);
if(bytesSent <= 0)
return false;
return true;
}
bool recv_size()
{
_clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (int)Timers.TIMEOUT_SIZE);
try
{
bytesReceived = _clientSocket.Receive(sizeBuffer, (int)BufferSize.BUFF_FILE_SIZE, SocketFlags.None);
}
catch (SocketException socEx)
{
return false;
}
// file size received
...
return true;
}
bool recv_file()
{
...
...
_clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, (int)Timers.TIMEOUT_FILE);
try
{
***// the 'fileBuff' here has the file size read previously!!!!!
bytesReceived = _clientSocket.Receive(fileBuff, (int)BufferSize.BUFF_FILE_SIZE, SocketFlags.None);***
}
catch (SocketException socEx)
{
return false;
}
// file size received
...
return true;
}