コード例 #1
0
        public virtual bool ProcessReceive(byte[] buffer, int offset, int count) //接收异步事件返回的数据,用于对数据进行缓存和分包
        {
            try
            {
                ActiveTime = DateTime.UtcNow;
                ReceiveBuffer.WriteBuffer(buffer, offset, count);

                int Len = BitConverter.ToInt32(buffer, offset); //取出信息长度
                offset += sizeof(int);

                // 收到的数据不全
                if (Len + sizeof(int) > count)
                {
                    return(true);
                }

                string msg = Encoding.UTF8.GetString(buffer, offset, Len);
                ReceiveBuffer.Clear(Len + sizeof(int));

                if (serverSocket.Receive != null)
                {
                    serverSocket.Receive(this, new ClientData(msg));
                }

                return(true);
            }
            catch (Exception e)
            {
                Global.Logger.Error(e.Message);
                Global.Logger.Error(e.StackTrace);
                return(false);
            }
        }
コード例 #2
0
        internal bool Receive(byte[] buffer, int offset, int count)
        {
            ReceiveBuffer.WriteBytes(buffer, offset, count);  // 写入数据内容
            bool result = true;

            while (ReceiveBuffer.DataCount > sizeof(int))
            {
                //按照长度分包
                int packetLength = BitConverter.ToInt32(ReceiveBuffer.Buffer, 0);           //获取包长度 // 老版代码

                if ((packetLength > 10 * 1024 * 1024) | (buffer.Length > 10 * 1024 * 1024)) //最大Buffer异常保护
                {
                    App.Logger.Error("内存超出, 数据不进行操作, 关闭远程连接");
                    return(false);
                }

                if ((ReceiveBuffer.DataCount - sizeof(int)) >= packetLength) //收到的数据达到包长度
                {
                    result = PacketProcess.Process(this, ReceiveBuffer.Buffer, sizeof(int), packetLength);
                    if (result)
                    {
                        ReceiveBuffer.Clear(packetLength + sizeof(int));
                    }
                    else
                    {
                        return(result);
                    }
                }
                else
                {
                    return(true);
                }
            }
            return(true);
        }
コード例 #3
0
        public virtual bool ProcessReceive(byte[] buffer, int offset, int count) //接收异步事件返回的数据,用于对数据进行缓存和分包
        {
            try
            {
                ActiveTime = DateTime.UtcNow;
                ReceiveBuffer.WriteBuffer(buffer, offset, count);

                int Len = BitConverter.ToInt32(buffer, offset); //取出信息长度
                offset += sizeof(int);

                // 收到的数据不全
                if (Len + sizeof(int) > count)
                {
                    return(true);
                }

                string msg = Encoding.UTF8.GetString(buffer, offset, Len);
                ReceiveBuffer.Clear(Len + sizeof(int));
                serverSocket.Receive(this, msg);
                return(true);
            }
            catch (Exception e)
            {
                Tools.MyLog.Error("Error: {0}\nStackTrace: {1}", e.Message, e.StackTrace);
                return(false);
            }
        }
コード例 #4
0
        private bool ProcessReceive(byte[] buffer, int offset, int count) //接收异步事件返回的数据,用于对数据进行缓存和分包
        {
            try
            {
                ActiveTime = DateTime.UtcNow;
                ReceiveBuffer.WriteBuffer(buffer, offset, count);

                int Len = BitConverter.ToInt32(buffer, offset); //取出信息长度
                offset += sizeof(int);

                // 收到的数据不全
                if (Len + sizeof(int) > count)
                {
                    return(true);
                }

                string msg = Encoding.UTF8.GetString(buffer, offset, Len);
                ReceiveBuffer.Clear(Len + sizeof(int));
                Receive(msg);
                return(true);
            }
            catch (Exception e)
            {
                MyLog.Error(e.Message + e.StackTrace);
                return(false);
            }
        }
コード例 #5
0
        /// <summary>
        /// 解析连接请求信息
        /// </summary>
        /// <param name="buffer">接收到的原始数量</param>
        /// <returns></returns>
        public static HttpRequest From(ReceiveBuffer buffer)
        {
            buffer.Position = 0;
            var bytes = buffer.ReadArray();

            buffer.Clear();
            return(HttpRequest.From(bytes, "ws"));
        }
コード例 #6
0
        public void ClearTest()
        {
            ReceiveBuffer target = new ReceiveBuffer(); // TODO: 初始化为适当的值

            target.Add(new byte[] { 1, 2 }, 0, 2);
            target.Clear();
            Assert.IsTrue(target.Length == 0);
        }
コード例 #7
0
        public void ClearTest1()
        {
            ReceiveBuffer target = new ReceiveBuffer(); // TODO: 初始化为适当的值

            target.Add(new byte[] { 1, 2 }, 0, 2);
            int count = 1; // TODO: 初始化为适当的值

            target.Clear(count);
            Assert.IsTrue(target.Length == 1 && target[0] == 2);
        }
コード例 #8
0
        /* Calling this function resets ReceiveData/SendDataLog to Empty and reset the number of bytes sent and received to zero */
        private void ClearOutput()
        {
            receiveBuffer.Clear();
            ReceiveData         = string.Empty;
            SendDataLog         = string.Empty;
            numberBytesSendInt  = 0;
            NumberBytesReceived = receiveBuffer.Count.ToString();
            NumberBytesSend     = numberBytesSendInt.ToString();

            PutLog("清空数据");
        }
コード例 #9
0
 /// <summary>
 /// Reset the object to init state.
 /// </summary>
 public void Reset()
 {
     Tag = null;
     // ClientSocket = null;
     // ClientID = default(long);
     IPEndPoint = null;
     ReceiveBuffer?.Clear();
     SendBuffer?.Clear();
     RecvSpeedController?.Reset();
     SendController?.Reset();
 }
コード例 #10
0
 /// <summary>
 /// Reset the object to init state.
 /// </summary>
 public void Reset()
 {
     Tag          = null;
     ClientSocket = null;
     ClientID     = default(long);
     IPEndPoint   = null;
     ReceiveBuffer?.Clear();
     Groups = null;
     Status = ClientStatus.Closed;
     RecvSpeedController?.Reset();
     SendController?.Reset();
     RecvRawMessage.ClientID       = default(long);
     RecvRawMessage.MessageRawData = default(ArraySegment <byte>);
     if (SockAsyncArgs != null)
     {
         SockAsyncArgs.AcceptSocket = null;
         SockAsyncArgs.UserToken    = null;
     }
 }
コード例 #11
0
        internal bool Receive(byte[] buffer, int offset, int count)
        {
            ReceiveBuffer.WriteBytes(buffer, offset, count);
            bool result = true;

            while (ReceiveBuffer.DataCount > sizeof(int))
            {
                int packetLength = BitConverter.ToInt32(ReceiveBuffer.Buffer, 0);

                if ((packetLength > 10 * 1024 * 1024) | (buffer.Length > 10 * 1024 * 1024))
                {
                    Console.WriteLine("Memory out , will close remote connect");
                    return(false);
                }

                if ((ReceiveBuffer.DataCount - sizeof(int)) >= packetLength)
                {
                    if (ProtocolMgr != null)
                    {
                        result = ProtocolMgr.Process(this, ReceiveBuffer.Buffer, sizeof(int), packetLength);
                        if (result)
                        {
                            ReceiveBuffer.Clear(packetLength + sizeof(int));
                        }
                        else
                        {
                            return(result);
                        }
                    }
                    else
                    {
                        return(result);
                    }
                }
                else
                {
                    return(true);
                }
            }
            return(true);
        }
コード例 #12
0
        /// <summary>
        /// 当接收到会话对象的数据时,将触发此方法
        /// </summary>
        /// <param name="session">会话对象</param>
        /// <param name="buffer">接收到的历史数据</param>
        /// <returns></returns>
        protected override void OnReceive(FastSession session, ReceiveBuffer buffer)
        {
            while (true)
            {
                FastPacket packet = null;
                try
                {
                    packet = FastPacket.From(buffer);
                }
                catch (Exception ex)
                {
                    buffer.Clear();
                    this.OnException(session, ex);
                }

                if (packet == null)
                {
                    break;
                }
                // 新线程处理业务内容
                Task.Factory.StartNew(() => this.OnRecvPacket(session, packet));
            }
        }
コード例 #13
0
        /// <summary>
        /// 解析连接请求信息
        /// </summary>
        /// <param name="buffer">接收到的原始数量</param>
        /// <returns></returns>
        public static HttpRequest From(ReceiveBuffer buffer)
        {
            buffer.Position = 0;
            var bytes = buffer.ReadArray();

            var request = HttpRequest.From(bytes, "http");

            if (request == null)
            {
                return(null);
            }

            if (string.Equals(request.Method, "POST", StringComparison.OrdinalIgnoreCase))
            {
                var contentLength = int.Parse(request["Content-Length"]);
                if (request.Body.Length < contentLength)
                {
                    return(null);
                }
            }

            buffer.Clear();
            return(request);
        }
コード例 #14
0
 /// <summary>
 /// 解析连接请求信息
 /// </summary>
 /// <param name="buffer">接收到的原始数量</param>
 /// <returns></returns>
 public static HttpRequest From(ReceiveBuffer buffer)
 {
     buffer.Position = 0;
     var bytes = buffer.ReadArray();
     buffer.Clear();
     return HttpRequest.From(bytes, "ws");
 }
コード例 #15
0
 protected override void onConnected()
 {
     base.onConnected();
     _buffer.Clear();
 }
コード例 #16
0
 public void Reset()
 {
     ReceiveBuffer.Clear();
 }
コード例 #17
0
        /// <summary>
        /// 解析请求的数据
        /// 返回请求数据包
        /// </summary>
        /// <param name="buffer">所有收到的数据</param>
        /// <returns></returns>
        public unsafe static FrameRequest From(ReceiveBuffer buffer)
        {
            if (buffer.Length < 2)
            {
                return(null);
            }

            ByteBits byte0     = buffer[0];
            var      fin       = byte0[0];
            var      frameCode = (FrameCodes)(byte)byte0.Take(4, 4);

            if (fin == false || frameCode == FrameCodes.Continuation)
            {
                return(null);
            }

            var      rsv   = byte0.Take(1, 3);
            ByteBits byte1 = buffer[1];
            var      mask  = byte1[0];

            if (mask == false || Enum.IsDefined(typeof(FrameCodes), frameCode) == false || rsv != 0)
            {
                return(null);
            }

            var contentLength = (int)byte1.Take(1, 7);

            buffer.Position = 2;

            if (contentLength == 127)
            {
                contentLength = (int)buffer.ReadUInt64();
            }
            else if (contentLength == 126)
            {
                contentLength = (int)buffer.ReadUInt16();
            }

            var packetLength = 6 + contentLength;

            if (buffer.Length < packetLength)
            {
                return(null);
            }

            var maskingKey = buffer.ReadArray(4);
            var content    = buffer.ReadArray(contentLength);

            buffer.Clear(packetLength);

            if (contentLength > 0)
            {
                fixed(byte *pcontent = &content[0], pmask = &maskingKey[0])
                {
                    for (var i = 0; i < contentLength; i++)
                    {
                        *(pcontent + i) = (byte)(*(pcontent + i) ^ *(pmask + i % 4));
                    }
                }
            }

            return(new FrameRequest
            {
                Fin = fin,
                Rsv = rsv,
                Mask = mask,
                Frame = frameCode,
                ContentLength = contentLength,
                MaskingKey = maskingKey,
                Content = content
            });
        }
コード例 #18
0
        /// <summary>
        /// 解析连接请求信息
        /// 如果数据未完整则返回null
        /// </summary>
        /// <param name="buffer">接收到的原始数量</param>
        /// <param name="localEndpoint">服务器的本地终结点</param>
        /// <param name="remoteEndpoint">远程端的IP和端口</param>
        /// <exception cref="HttpException"></exception>
        /// <returns></returns>
        public static HttpRequest Parse(ReceiveBuffer buffer, IPEndPoint localEndpoint, IPEndPoint remoteEndpoint)
        {
            buffer.Position = 0;
            var doubleCrlf = Encoding.ASCII.GetBytes("\r\n\r\n");
            var headerIndex = buffer.IndexOf(doubleCrlf);
            if (headerIndex < 0)
            {
                return null; // 数据未完整
            }

            var headerLength = headerIndex + doubleCrlf.Length;
            var headerString = buffer.ReadString(headerLength, Encoding.ASCII);
            const string pattern = @"^(?<method>[^\s]+)\s(?<path>[^\s]+)\sHTTP\/1\.1\r\n" +
                @"((?<field_name>[^:\r\n]+):\s(?<field_value>[^\r\n]*)\r\n)+" +
                @"\r\n";

            var match = Regex.Match(headerString, pattern, RegexOptions.IgnoreCase);
            if (match.Success == false)
            {
                throw new HttpException(400, "请求中有语法问题,或不能满足请求");
            }

            var httpMethod = GetHttpMethod(match.Groups["method"].Value);
            var httpHeader = new HttpHeader(match.Groups["field_name"].Captures, match.Groups["field_value"].Captures);
            var contentLength = httpHeader.TryGet<int>("Content-Length");

            if (httpMethod == HttpMethod.POST && buffer.Length - headerLength < contentLength)
            {
                return null; // 数据未完整
            }

            var request = new HttpRequest
            {
                LocalEndPoint = localEndpoint,
                RemoteEndPoint = remoteEndpoint,
                HttpMethod = httpMethod,
                Headers = httpHeader
            };

            request.Url = new Uri("http://localhost:" + localEndpoint.Port + match.Groups["path"].Value);
            request.Path = request.Url.AbsolutePath;
            request.Query = new HttpNameValueCollection(HttpUtility.UrlDecode(request.Url.Query.TrimStart('?')));

            if (httpMethod == HttpMethod.GET)
            {
                request.InputStrem = new byte[0];
                request.Form = new HttpNameValueCollection();
                request.Files = new HttpFile[0];
            }
            else
            {
                request.InputStrem = buffer.ReadArray(contentLength);
                buffer.Position = headerLength;
                HttpRequest.GeneratePostFormAndFiles(request, buffer);
            }

            buffer.Clear(headerLength + contentLength);
            return request;
        }
コード例 #19
0
        /// <summary>
        /// 解析请求的数据
        /// 返回请求数据包
        /// </summary>
        /// <param name="buffer">所有收到的数据</param>  
        /// <returns></returns>
        public static unsafe FrameRequest From(ReceiveBuffer buffer)
        {
            if (buffer.Length < 2)
            {
                return null;
            }

            ByteBits byte0 = buffer[0];
            var fin = byte0[0];
            var frameCode = (FrameCodes)(byte)byte0.Take(4, 4);

            if (fin == false || frameCode == FrameCodes.Continuation)
            {
                return null;
            }

            var rsv = byte0.Take(1, 3);
            ByteBits byte1 = buffer[1];
            var mask = byte1[0];

            if (mask == false || Enum.IsDefined(typeof(FrameCodes), frameCode) == false || rsv != 0)
            {
                return null;
            }

            var contentLength = (int)byte1.Take(1, 7);
            buffer.Position = 2;

            if (contentLength == 127)
            {
                contentLength = (int)buffer.ReadUInt64();
            }
            else if (contentLength == 126)
            {
                contentLength = (int)buffer.ReadUInt16();
            }

            var packetLength = 6 + contentLength;
            if (buffer.Length < packetLength)
            {
                return null;
            }

            var maskingKey = buffer.ReadArray(4);
            var content = buffer.ReadArray(contentLength);
            buffer.Clear(packetLength);

            if (contentLength > 0)
            {
                fixed (byte* pcontent = &content[0], pmask = &maskingKey[0])
                {
                    for (var i = 0; i < contentLength; i++)
                    {
                        *(pcontent + i) = (byte)(*(pcontent + i) ^ *(pmask + i % 4));
                    }
                }
            }

            return new FrameRequest
            {
                Fin = fin,
                Rsv = rsv,
                Mask = mask,
                Frame = frameCode,
                ContentLength = contentLength,
                MaskingKey = maskingKey,
                Content = content
            };
        }
コード例 #20
0
 protected override void OnReceive(SessionBase session, ReceiveBuffer buffer)
 {
     buffer.Clear();
 }
コード例 #21
0
ファイル: FastPacket.cs プロジェクト: dzvane/NetworkSocket
        /// <summary>
        /// 解析一个数据包       
        /// 不足一个封包时返回null
        /// </summary>
        /// <param name="buffer">接收到的历史数据</param>
        /// <exception cref="ProtocolException"></exception>
        /// <returns></returns>
        public static FastPacket From(ReceiveBuffer buffer)
        {
            if (buffer.Length < 4)
            {
                return null;
            }

            buffer.Position = 0;
            var totalBytes = buffer.ReadInt32();
            const int packegMaxSize = 10 * 1204 * 1024; // 10M
            if (totalBytes > packegMaxSize)
            {
                throw new ProtocolException();
            }

            // 少于15字节是异常数据,清除收到的所有数据
            const int packetMinSize = 15;
            if (totalBytes < packetMinSize)
            {
                throw new ProtocolException();
            }

            // 数据包未接收完整
            if (buffer.Length < totalBytes)
            {
                return null;
            }

            // api名称数据长度
            var apiNameLength = buffer.ReadByte();
            if (totalBytes < apiNameLength + packetMinSize)
            {
                throw new ProtocolException();
            }

            // api名称数据
            var apiNameBytes = buffer.ReadArray(apiNameLength);
            // 标识符
            var id = buffer.ReadInt64();
            // 是否为客户端封包
            var isFromClient = buffer.ReadBoolean();
            // 是否异常
            var isException = buffer.ReadBoolean();
            // 实体数据
            var body = buffer.ReadArray(totalBytes - buffer.Position);

            // 清空本条数据
            buffer.Clear(totalBytes);

            var apiName = Encoding.UTF8.GetString(apiNameBytes);
            var packet = new FastPacket(apiName, id, isFromClient)
            {
                TotalBytes = totalBytes,
                ApiNameLength = apiNameLength,
                IsException = isException,
                Body = body
            };
            return packet;
        }
コード例 #22
0
        /// <summary>
        /// 解析连接请求信息
        /// </summary>
        /// <param name="buffer">接收到的原始数量</param>
        /// <param name="localEndpoint">服务器的本地终结点</param>
        /// <param name="remoteEndpoint">远程端的IP和端口</param>
        /// <returns></returns>
        public static HttpRequest From(ReceiveBuffer buffer, IPEndPoint localEndpoint, IPEndPoint remoteEndpoint)
        {
            buffer.Position = 0;
            var bytes = buffer.ReadArray();

            var request = HttpRequest.From(bytes, localEndpoint, remoteEndpoint);
            if (request != null)
            {
                buffer.Clear();
            }
            return request;
        }
コード例 #23
0
ファイル: FastPacket.cs プロジェクト: tenove/NetworkSocket
        /// <summary>
        /// 解析一个数据包
        /// 不足一个封包时返回null
        /// </summary>
        /// <param name="buffer">接收到的历史数据</param>
        /// <exception cref="ProtocolException"></exception>
        /// <returns></returns>
        public static FastPacket From(ReceiveBuffer buffer)
        {
            if (buffer.Length < 4)
            {
                return(null);
            }

            buffer.Position = 0;
            var       totalBytes    = buffer.ReadInt32();
            const int packegMaxSize = 10 * 1204 * 1024; // 10M

            if (totalBytes > packegMaxSize)
            {
                throw new ProtocolException();
            }

            // 少于15字节是异常数据,清除收到的所有数据
            const int packetMinSize = 15;

            if (totalBytes < packetMinSize)
            {
                throw new ProtocolException();
            }

            // 数据包未接收完整
            if (buffer.Length < totalBytes)
            {
                return(null);
            }

            // api名称数据长度
            var apiNameLength = buffer.ReadByte();

            if (totalBytes < apiNameLength + packetMinSize)
            {
                throw new ProtocolException();
            }

            // api名称数据
            var apiNameBytes = buffer.ReadArray(apiNameLength);
            // 标识符
            var id = buffer.ReadInt64();
            // 是否为客户端封包
            var isFromClient = buffer.ReadBoolean();
            // 是否异常
            var isException = buffer.ReadBoolean();
            // 实体数据
            var body = buffer.ReadArray(totalBytes - buffer.Position);

            // 清空本条数据
            buffer.Clear(totalBytes);

            var apiName = Encoding.UTF8.GetString(apiNameBytes);
            var packet  = new FastPacket(apiName, id, isFromClient)
            {
                TotalBytes    = totalBytes,
                ApiNameLength = apiNameLength,
                IsException   = isException,
                Body          = body
            };

            return(packet);
        }
コード例 #24
0
ファイル: HttpRequest.cs プロジェクト: tenove/NetworkSocket
        /// <summary>
        /// 解析连接请求信息
        /// 如果数据未完整则返回null
        /// </summary>
        /// <param name="buffer">接收到的原始数量</param>
        /// <param name="localEndpoint">服务器的本地终结点</param>
        /// <param name="remoteEndpoint">远程端的IP和端口</param>
        /// <exception cref="HttpException"></exception>
        /// <returns></returns>
        public static HttpRequest Parse(ReceiveBuffer buffer, IPEndPoint localEndpoint, IPEndPoint remoteEndpoint)
        {
            buffer.Position = 0;
            var doubleCrlf  = Encoding.ASCII.GetBytes("\r\n\r\n");
            var headerIndex = buffer.IndexOf(doubleCrlf);

            if (headerIndex < 0)
            {
                return(null); // 数据未完整
            }

            var          headerLength = headerIndex + doubleCrlf.Length;
            var          headerString = buffer.ReadString(headerLength, Encoding.ASCII);
            const string pattern      = @"^(?<method>[^\s]+)\s(?<path>[^\s]+)\sHTTP\/1\.1\r\n" +
                                        @"((?<field_name>[^:\r\n]+):\s(?<field_value>[^\r\n]*)\r\n)+" +
                                        @"\r\n";

            var match = Regex.Match(headerString, pattern, RegexOptions.IgnoreCase);

            if (match.Success == false)
            {
                throw new HttpException(400, "请求中有语法问题,或不能满足请求");
            }

            var httpMethod    = GetHttpMethod(match.Groups["method"].Value);
            var httpHeader    = new HttpHeader(match.Groups["field_name"].Captures, match.Groups["field_value"].Captures);
            var contentLength = httpHeader.TryGet <int>("Content-Length");

            if (httpMethod == HttpMethod.POST && buffer.Length - headerLength < contentLength)
            {
                return(null); // 数据未完整
            }

            var request = new HttpRequest
            {
                LocalEndPoint  = localEndpoint,
                RemoteEndPoint = remoteEndpoint,
                HttpMethod     = httpMethod,
                Headers        = httpHeader
            };

            request.Url   = new Uri("http://localhost:" + localEndpoint.Port + match.Groups["path"].Value);
            request.Path  = request.Url.AbsolutePath;
            request.Query = new HttpNameValueCollection(HttpUtility.UrlDecode(request.Url.Query.TrimStart('?')));

            if (httpMethod == HttpMethod.GET)
            {
                request.InputStrem = new byte[0];
                request.Form       = new HttpNameValueCollection();
                request.Files      = new HttpFile[0];
            }
            else
            {
                request.InputStrem = buffer.ReadArray(contentLength);
                buffer.Position    = headerLength;
                HttpRequest.GeneratePostFormAndFiles(request, buffer);
            }

            buffer.Clear(headerLength + contentLength);
            return(request);
        }