0

我正在学习使用 MSDN 教程使用 SocketAsyncEventArgs 的东西。我只是想知道一些事情,即如何实现具有全双工功能的服务器。

目前,MSDN 示例教您创建一个服务器,该服务器首先侦听,然后在收到某些内容时将其发回。只有这样服务器才会再次开始监听。

我想出自己的解决方案的问题是该SocketAsyncEventArgs对象只有一个事件,Completed即为发送和接收而触发。它没有其他事件。

我在一些翻译得很糟糕的网站上读到

必须使用两个SocketAsyncEventArgs,一个接收一个发。

-未知

我发现这个所谓的“增强”套接字实现有少量令人不安的信息......

这是我的一些代码,所以你可以看到我在做什么。

        //Called when a SocketAsyncEventArgs raises the completed event
        private void ProcessReceive(SocketAsyncEventArgs e)
        {
            Token Token = (Token)e.UserToken;

            if(e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
            {
                Interlocked.Add(ref TotalBytesRead, e.BytesTransferred);
                Console.WriteLine(String.Format("Received from {0}", ((Token)e.UserToken).Socket.RemoteEndPoint.ToString()));

                bool willRaiseEvent = ((Token)e.UserToken).Socket.ReceiveAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessReceive(e);
                }
            }
            else
            {
                CloseClientSocket(e);
            }
        }

        private void ProcessSend(SocketAsyncEventArgs e)
        {
            if (e.SocketError == SocketError.Success)
            {
                // done echoing data back to the client
                Token token = (Token)e.UserToken;
                // read the next block of data send from the client
                bool willRaiseEvent = token.Socket.ReceiveAsync(e);
                if (!willRaiseEvent)
                {
                    ProcessReceive(e);
                }
            }
            else
            {
                CloseClientSocket(e);
            }
        }

        void IOCompleted(object sender, SocketAsyncEventArgs e)
        {
            // determine which type of operation just completed and call the associated handler
            switch (e.LastOperation)
            {
                case SocketAsyncOperation.Receive:
                    ProcessReceive(e);
                    break;
                case SocketAsyncOperation.Send:
                    ProcessSend(e);
                    break;
                default:
                    throw new ArgumentException("The last operation completed on the socket was not a receive or send");
            }

        }

谢谢!

4

1 回答 1

0

SocketAsyncEventArgs解决方案是为两者创建一个单独的SendReceive

它需要更多的内存但并不多,因为不需要为Sendargs 分配缓冲区。

于 2017-02-06T13:57:04.110 回答