コード例 #1
0
ファイル: TcpSocketClient.cs プロジェクト: 0000duck/WCS-HK
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="client"></param>
        private void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                socketReceiveObject            = new TcpReceiveObject();
                socketReceiveObject.workSocket = client;

                // Begin receiving the data from the remote device.
                client.BeginReceive(socketReceiveObject.buffer, 0, TcpReceiveObject.BufferSize, 0,
                                    new AsyncCallback(ReceiveCallback), socketReceiveObject);
            }
            catch (Exception ex)
            {
                _log.WriteLog("Receive error", ex);
            }
        }
コード例 #2
0
ファイル: TcpSocketClient.cs プロジェクト: 0000duck/WCS-HK
        /// <summary>
        /// 接收回调
        /// </summary>
        /// <param name="AsynRes"></param>
        private void ReceiveCallback(IAsyncResult AsynRes)
        {
            try
            {
                // Retrieve the state object and the client socket
                // from the asynchronous state object.
                TcpReceiveObject state  = (TcpReceiveObject)AsynRes.AsyncState;
                Socket           client = state.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(AsynRes);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.ReceiveInfo.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                    if (socketCfg.MultiplyReceiveMode)//只是返回了一部分数据,需要再继续等待对方发送其他数据
                    {
                        // Get the rest of the data.
                        client.BeginReceive(state.buffer, 0, TcpReceiveObject.BufferSize, 0,
                                            new AsyncCallback(ReceiveCallback), state);
                    }
                }

                if (bytesRead == 0 || socketCfg.MultiplyReceiveMode == false)//数据接收完成,或者数据已经一次性接收完毕
                {
                    // All the data has arrived; put it in response.
                    if (state.ReceiveInfo.Length > 1)
                    {
                        Raise_MessageReceivedEvent(client, state.ReceiveInfo.ToString());
                    }
                    // Signal that all bytes have been received.
                    receiveDone.Set();
                }
            }
            catch (Exception ex)
            {
                _log.WriteLog("ReceiveCallback error", ex);
            }
        }