简体   繁体   English

异步客户端句柄接收?

[英]Async client handle receive?

I was told several times that async is better or that I should use async instead of sync sockets and as such started learning it, but am already having difficult. 我多次被告知异步更好,或者我应该使用异步而不是同步套接字,因此开始学习它,但是已经很困难了。

I've got the basic feel of how the callback works and how to establish a connection. 我对回调如何工作以及如何建立连接有基本的了解。

I am using this msdn code as reference! 我正在使用此msdn代码作为参考!

A few problems I am having with the code: 我的代码有一些问题:

  • Currently that code will connect to the server, send a text, read the response and exit. 当前,该代码将连接到服务器,发送文本,读取响应并退出。 How do I do so I can keep receiving the data until either the server disconnects me and/or I end it by myself ? 我该如何做才能继续接收数据,直到服务器断开我的连接和/或我自己结束该数据为止? I am not much sure on how I should do it, if I would need to wrap it on a thread with while or simple call that Receive again once the ReceiveCallback is done. 如果我需要使用while或简单的调用将其包装在线程上,一旦ReceiveCallback完成,则再次接收,我不太确定该怎么做。

  • Another things I've noticed is when it connects, the socket is assigned to client but the code itself is always reassigning the client socket which I don't understand very well compared to the sync socket we have a main socket that we are always consulting etc. 我注意到的另一件事是,当连接时,套接字已分配给客户端,但是代码本身总是在重新分配客户端套接字,与同步套接字相比,我不太了解,我们有一个主套接字,我们一直在咨询等等

I am not sure on how old the reference I am using is but would appreciate if you could help me with examples of what I have pointed out as it is easier for me to understand. 我不确定我使用的参考文献的年龄,但是如果您能通过我所指出的示例帮助我,将不胜感激,因为它使我更容易理解。

UPDATE: 更新:

    private void SetupRecieveCallback(Socket sock)
    {
        new Thread(
            delegate()
            {
                while (isReceiving)
                {
                    _receiveQueue.Reset();
                    try
                    {
                        AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
                        sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error("Setup Recieve Callback failed! " + ex.Message);
                    }
                    _receiveQueue.WaitOne();
                }
            }
        ).Start();
        /*
                    // The original code
        try
        {
            AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
            sock.BeginReceive(m_byBuff, 0, m_byBuff.Length, SocketFlags.None, recieveData, sock);
        }
        catch (Exception ex)
        {
            _logger.Error("Setup Recieve Callback failed! " + ex.Message);
        }
        */
    }

Simply call BeginReceive() again in the callback to keep receiving. 只需在回调中再次调用BeginReceive()即可继续接收。 When the server breaks the connection then your callback will be called and EndReceive() throws an ObjectDisposedException. 当服务器断开连接时,您的回调将被调用,EndReceive()引发ObjectDisposedException。 That's how you know to stop calling BeginReceive(). 这就是您停止调用BeginReceive()的方式。

Second question is harder to decode (ask only one). 第二个问题更难解码(只问一个)。 I'm guessing you are puzzled about this statement: 我猜你对这个说法感到困惑:

private static void ConnectCallback(IAsyncResult ar) {
    try {
        // Retrieve the socket from the state object.
        Socket client = (Socket) ar.AsyncState;
        // etc..

No reassigning the socket is happening here. 这里没有发生重新分配套接字的情况。 The code simply retrieves a reference to the original socket. 该代码仅检索对原始套接字的引用。 Which is a useful technique, it allows this callback to be used by more than one connection. 这是一项有用的技术,它允许多个连接使用此回调。 The ar.AsyncState value got to be the socket by this statement: 该语句将ar.AsyncState值设置为套接字:

        client.BeginConnect( remoteEP, 
            new AsyncCallback(ConnectCallback), client);

Note how client is passed to the AsyncCallback constructor. 请注意如何将客户端传递给AsyncCallback构造函数。 The exact same client that's retrieved in the callback. 在回调中检索到的客户端完全相同。 Any object can be passed. 可以传递任何对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM