コード例 #1
0
        /// <summary>
        /// Asynchronously writes <paramref name="content"/> to the provided <paramref name="stream"/>.
        /// </summary>
        /// <param name="stream">The stream to write to.</param>
        /// <param name="content">The text to write.</param>
        protected virtual void Write(Stream stream, string content)
        {
            if (_disposed || !stream.CanWrite)
            {
                Dispose();
                return;
            }

            _log.Debug(content);

            try
            {
                byte[] response = ControlStreamEncoding.GetBytes(string.Concat(content, "\r\n"));

                stream.BeginWrite(response, 0, response.Length, WriteCallback, stream);
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                Dispose();
            }
        }
コード例 #2
0
        private void ReadCallback(IAsyncResult result)
        {
            if (result == null)
            {
                Dispose();
                return;
            }

            Stream stream = result.AsyncState as Stream;

            if (_disposed || stream == null || !stream.CanRead)
            {
                Dispose();
                return;
            }

            int bytesRead = 0;

            try
            {
                bytesRead = stream.EndRead(result);
            }
            catch (IOException ex)
            {
                _log.Error(ex);
            }

            // End read returns 0 bytes if the socket closed...
            if (bytesRead == 0)
            {
                Dispose();
                return;
            }

            string line = ControlStreamEncoding.GetString(_buffer, 0, bytesRead);

            _commandBuffer.Append(line);

            _log.Debug(line);

            // 信息没有以预定的结束符结尾,后面可能还有信息,继续读(_commandBuffer命令缓冲区保留)
            // We don't have the full message yet, so keep reading.
            if (!_commandBuffer.EndsWith(ExpectedTerminator))
            {
                Read();
                return;
            }

            string command = _commandBuffer.ToString().Trim();

            _log.Debug(command);

            Command cmd = ParseCommandLine(command);

            // 清除命令缓冲区(_commandBuffer),准备下次读取
            // Clear the command buffer, so we can keep listening for more commands.
            _commandBuffer.Clear();
            command = null;

            Response r = HandleCommand(cmd);

            if (ControlClient != null && ControlClient.Connected)
            {
                if (r != null)  //FIXED:可以不响应
                {
                    Write(r);
                }

                if (r.ShouldQuit)
                {
                    Dispose();
                    return;
                }

                OnCommandComplete(cmd);

                cmd = null;
                r   = null;

                Read();
            }
        }