How to abort socket's BeginReceive()?

后端 未结 7 2079
夕颜
夕颜 2020-12-05 06:17

Naturally, BeginReceive() will never end if there\'s no data. MSDN suggests that calling Close() would abort BeginReceive().

7条回答
  •  半阙折子戏
    2020-12-05 07:05

    In the ReceiveCallback I checked client.Connected within the try block. Now, when data is received after BeginReceive, I can call client.Close(); This way, I do not see exceptions. I send modbus-TCP requests every 200mS, and get responses in time. The console output looks clean. I used a windows forms app, to test this.

        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.  
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;
                if (client.Connected)
                {
                    // Read data from the remote device.  
                    state.dataSize = client.EndReceive(ar);
                    if (state.dataSize > 0)
                    {
                        Console.WriteLine("Received: " + state.dataSize.ToString() + " bytes from server");
                        // There might be more data, so store the data received so far.  
                        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, state.dataSize));
                        //  Get the rest of the data.  
                        client.BeginReceive(state.buffer, 0, StateObject.BUFFER_SIZE, 0,
                            new AsyncCallback(ReceiveCallback), state);
    
                        state.dataSizeReceived = true;           //received data size?
    
                        dataSize = state.dataSize;
                        buffer = state.buffer.ToArray();
                        dataSizeReceived = state.dataSizeReceived;
    
                        string hex = ByteArrayToString(state.buffer, state.dataSize);
                        Console.WriteLine("<- " + hex);
    
                        receiveDone.Set();
                        client.Close();
                    }
                    else
                    {
                        Console.WriteLine("All the data has arrived");
                        // All the data has arrived; put it in response.  
                        if (state.sb.Length > 1)
                        {
                            Console.WriteLine("Length: " + state.sb.Length.ToString());
                        }
                        // Signal that all bytes have been received.  
                        receiveDone.Set();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    

提交回复
热议问题