C#Socket ReceiveAsync

时间:2015-08-24 07:40:46

标签: c# sockets asyncsocket

我习惯于同步套接字并且有一些令人头疼的事情要达到我现在所处的地步,尤其是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有人指出我可能做错了或需要改变的事情

0 个答案:

没有答案