gpt4 book ai didi

C# 套接字 ReceiveAsync

转载 作者:行者123 更新时间:2023-11-30 16:52:47 25 4
gpt4 key购买 nike

我已经习惯了同步套接字,但为了达到现在的状态,我有些头疼,尤其是在 Socket.Receive(..) 并不总是接收到所有字节的情况下

这是我以前使用的代码

    public byte[] Receive(int size)
{
var buffer = new byte[size];
var r = 0;
do
{
// ReSharper disable once InconsistentlySynchronizedField
var c = _clientSocket.Receive(buffer, r, size - r, SocketFlags.None);
if (c == 0)
{
throw new SocketExtendedException();
}
r += c;
} while (r != buffer.Length);
return buffer;
}

现在我开始在 Windows Phone 中使用套接字,但是 .Receive(..) 不可用,我设法让 Socket.ReceiveAsync(..) 工作但是我很担心(到目前为止没有发生任何问题)这是我的新代码,我没有实现检查是否已收到所有字节,也不知道我是否必须使用以下代码

    private byte[] ReadBySize(int size = 4)
{
var readEvent = new AutoResetEvent(false);
var buffer = new byte[size];
var recieveArgs = new SocketAsyncEventArgs()
{
UserToken = readEvent
};
recieveArgs.SetBuffer(buffer, 0, size);
recieveArgs.Completed += recieveArgs_Completed;
_connecter.ReceiveAsync(recieveArgs);
readEvent.WaitOne();

if (recieveArgs.BytesTransferred == 0)
{
if (recieveArgs.SocketError != SocketError.Success)
throw new SocketException((int)recieveArgs.SocketError);
throw new CommunicationException();
}
return buffer;
}

void recieveArgs_Completed(object sender, SocketAsyncEventArgs e)
{
var are = (AutoResetEvent)e.UserToken;
are.Set();
}

这是我第一次使用 ReceiveAsync 谁能指出我可能做错的或需要更改的地方

最佳答案

好吧,我去拿了一个大缓冲区并分批发送,中间有一个 sleep 间隔以复制“并非所有字节都收到”所以我上面的代码没有收到所有字节。对于那些也使用 ReceiveAsync(..) 的人,这里是我的有效代码

    private byte[] ReadBySize(int size = 4)
{
var readEvent = new AutoResetEvent(false);
var buffer = new byte[size]; //Receive buffer
var totalRecieved = 0;
do
{
var recieveArgs = new SocketAsyncEventArgs()
{
UserToken = readEvent
};
recieveArgs.SetBuffer(buffer, totalRecieved, size - totalRecieved);//Receive bytes from x to total - x, x is the number of bytes already recieved
recieveArgs.Completed += recieveArgs_Completed;
_connecter.ReceiveAsync(recieveArgs);
readEvent.WaitOne();//Wait for recieve

if (recieveArgs.BytesTransferred == 0)//If now bytes are recieved then there is an error
{
if (recieveArgs.SocketError != SocketError.Success)
throw new ReadException(ReadExceptionCode.UnexpectedDisconnect,"Unexpected Disconnect");
throw new ReadException(ReadExceptionCode.DisconnectGracefully);
}
totalRecieved += recieveArgs.BytesTransferred;

} while (totalRecieved != size);//Check if all bytes has been received
return buffer;
}

void recieveArgs_Completed(object sender, SocketAsyncEventArgs e)
{
var are = (AutoResetEvent)e.UserToken;
are.Set();
}

我使用 Socket 应用程序的方式是发送一个包含一些变量的 Buffer

[0] -> 0,1,2 0 is keep alive, 1 means there are data, 2 means a type off error occured
[1,2,3,4] size of the actual buffer I am sending
[x(size of 1,2,3,4)] the actual 'Serialized' data buffer

关于C# 套接字 ReceiveAsync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32176826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com