Exemple #1
0
        /// <summary>
        /// 发送指令
        /// 接收多个响应包
        /// </summary>
        /// <param name="request">请求指令</param>
        /// <returns></returns>
        public IEnumerable <ResponseHeader> Sends(RequestHeader request)
        {
            if (this.socket == null)
            {
                this.socket = new Socket(this.ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            }
            if (this.socket.Connected == false)
            {
                this.socket.Connect(this.ipEndPoint);
            }

            // 将指令包解析发送
            this.socket.Send(request.ToByteArray());
            // 集合恢复
            this.byteBuilder.Clear();
            // 响应包集合
            var responseList = new List <ResponseHeader>();

            while (true)
            {
                // 接收数据
                int readByte = this.socket.Receive(this.socketBuffer);
                // 放到数据区
                this.byteBuilder.Add(this.socketBuffer, 0, readByte);
                // 包长
                int packetLength = 0;

                // 把接收到的数据(也许还不完整)拆分为包
                while (this.byteBuilder.Length >= 12 && (packetLength = this.byteBuilder.ToInt32(8) + 24) <= this.byteBuilder.Length)
                {
                    // 把数据包取出
                    var packetBytes = this.byteBuilder.ReadRange(packetLength);
                    var response    = new ResponseHeader(packetBytes);
                    responseList.Add(response);

                    // 非stat操作都是只有一个响应包
                    // stat操作的最后一个包是空包,占24字节
                    // stat操作有误的话也只返回一个响应包,为非No_Error状态
                    if (response.OpCode != OpCodes.Stat || packetLength == 24 || response.Status != OprationStatus.No_Error)
                    {
                        return(responseList);
                    }
                }
            }
        }
Exemple #2
0
 /// <summary>
 /// 发送指令
 /// 只取其中第一个响应包
 /// </summary>
 /// <param name="request">请求指令</param>
 /// <returns></returns>
 public ResponseHeader Send(RequestHeader request)
 {
     return(this.Sends(request).FirstOrDefault());
 }