简体   繁体   中英

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!

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.

  • 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. When the server breaks the connection then your callback will be called and EndReceive() throws an ObjectDisposedException. That's how you know to stop calling 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:

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

Note how client is passed to the AsyncCallback constructor. The exact same client that's retrieved in the callback. Any object can be passed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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