我正在尝试实现将请求的文件发送到客户端的文件服务器。 我使用TCP协议实现了服务器和客户端的发送和接收部分。
我的服务器发送从数据包队列中出队的数据包,直到数据包队列为空,并且我的客户端接收,直到接收到的数据包编号与所需的数据包编号相同为止。
我使用了.Net框架中的SendAsync()和ReceiveAsync()方法。
我的程序在调试时似乎没有问题,但实际上, 客户端似乎错过了一些从服务器发送的数据包。即使服务器发送了数据包,由于某种原因,客户端也无法接收到某些数据包。我不知道这怎么发生。
TCP协议不能确保接收服务器发送的每个数据包吗? 您有任何线索为什么会这样吗?
这是我的代码。 Receive_completed是ReceiveAsync()的回调方法,该方法在之后 ReceuveAsync已完成 并且Process_receive函数始终从ReceiveAsync()读取每个接收到的字节,如果已完成读取数据包,则返回true(否则,返回false,并且将再次调用Receive()方法)
和..忽略OperationCompleted和_receivedProperly ..
internal void Receive()//method for receiving the call
{
if (_operationState)
{
try
{
bool pending =_user.ClientSocket.ReceiveAsync(_receiveArg); // This will spawn a new thread and call Receive_completed as callback method
if (pending == false)
{
_receivePendingThread = new Thread(CallReceiveCompleted); //Start New thread
_receivePendingThread.Start();
}
}
catch (Exception exception)
{
ExceptionHandler(exception, CommunicatorError.ObjectDisposed);
}
}
}
private void Receive_completed(object sender, SocketAsyncEventArgs e)
{
if (e.LastOperation == SocketAsyncOperation.Receive)
{
bool transferCompleted = false;
try
{
if (e.BytesTransferred == 0)
{
throw new Exception("Socket Closed");
}
if (e.SocketError != SocketError.Success)
{
throw new Exception("Socket Error Occured");
}
}
catch (Exception exception)
{
ExceptionHandler(exception, CommunicatorError.SocketError);
return;
} //Checks for received bytes
//call process_receive here
transferCompleted = Process_receive(); //returns if more packets are left or not (This method Gurantees reading all received bytes from ReceiveAsync()
if (_receivedProperly&& _operationState) //Succeded process
{
if (transferCompleted && _operationState) Receive();//Receive if more bytes are left
else if (_operationState)
{// No more packets to be accepted additionally
CallReceiveCompleted();// Start Callback method
}
}
}
}