예제 #1
0
 public override void WriteCommand(INetCommand command, INetSession session)
 {
     if (command is HandshakeResponseCommand)
     {
         HandshakeResponseCommand response = command as HandshakeResponseCommand;
         Byte[] responseData = response.GetResponseData(session);
         session.WriteBytes(responseData, 0, responseData.Length);
     }
     else if (command is FrameCommandBase)
     {
         FrameStreamWriter writer = new FrameStreamWriter(command as FrameCommandBase);
         writer.Write(session);
     }
 }
예제 #2
0
        protected override void AsyncEventArgs_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e)
        {
            //if (e.BytesTransferred <= 0)
            //{
            //    Close();
            //    return;
            //}

            if (e.SocketError != SocketError.Success)
            {
                Debug.WriteLine(String.Format("接收数据时发生异常:{0} {1}", e.SocketError, e.RemoteEndPoint));
                Offline();
                logger.Error("接收数据时发生异常:{0} {1}", e.SocketError, e.RemoteEndPoint);
                return;
            }

            if (e.BytesTransferred == 0)
            {
                Close();
                return;
            }

            ReceivedBytes += e.BytesTransferred - e.Offset;

            for (int i = e.Offset; i < e.Offset + e.BytesTransferred; i++)
            {
                try
                {
                    frameStream.WriteByte(e.Buffer[i]);
                    frameStream.Flush();
                    if (isNoCheck && noCheckCount > 0)
                    {
                        noCheckCount--;
                        continue;
                    }
                    else if (isNoCheck)
                    {
                        isNoCheck    = false;
                        noCheckCount = 0;
                    }

                    if (!IsHandShake && Protocol.IsFrameEnd(frameStream))
                    {
                        frameStream.Position = 0;
                        HandshakeRequestCommand  command     = Protocol.GetCommand(this, frameStream) as HandshakeRequestCommand;
                        HandshakeResponseCommand responseCmd = null;

                        if (command != null)
                        {
                            ProtocolVersion      = command.GetHeader(WebSocketHeader.SecWebSocketAccept) ?? "";
                            this.Url             = command.GetHeader(WebSocketHeader.Url) ?? "";
                            frameStream.Position = 0;
                            frameStream.SetLength(0);
                            responseCmd = command.Execute(this) as HandshakeResponseCommand;
                            if (responseCmd != null && !isClosed)
                            {
                                FrameReader = new FrameStreamReader(frameStream);
                            }
                        }

                        if (responseCmd != null)
                        {
                            Protocol.WriteCommand(responseCmd, this);
                            IsHandShake = true;
                            OnHandshakeCompleted();
                            logger.Debug("客户端握手成功:{0} {1}", SessionID, EndPoint);
                        }
                        else
                        {
                            logger.Warn("客户端握手失败:{0} {1}", SessionID, EndPoint);
                            this.Close();
                        }
                    }
                    else if (IsHandShake)
                    {
                        bool isSuccess = FrameReader.ProcessFrame(this);
                        if (!isSuccess)
                        {
                            HttpCodeResponseCommand cmd = new HttpCodeResponseCommand();
                            cmd.SetHeader(WebSocketHeader.HttpCode, "1002");
                            sendOverClosed = true;
                            Protocol.WriteCommand(cmd, this);
                            logger.Error("接收数据帧发生异常:{0} {1}", SessionID, EndPoint);
                        }
                        else
                        {
                            //
                            if (FrameReader.IsCompleted)
                            {
                                frameStream.Position = 0;
                                frameStream.SetLength(0);
                                logger.Trace("收到数据帧:{0} {1} {2}", SessionID, EndPoint, FrameReader.ToString());
                                FrameCommandBase command = WebSocketCommandFactory.CreateCommand(FrameReader);
                                if (command != null)
                                {
                                    command = command.Execute(this) as FrameCommandBase;
                                    if (command != null)
                                    {
                                        Protocol.WriteCommand(command, this);
                                    }
                                }
                                if (!this.isClosed)
                                {
                                    FrameReader = new FrameStreamReader(frameStream);
                                }
                            }
                            else if (FrameReader.IsContinue)
                            {
                                frameStream.Position = 0;
                                frameStream.SetLength(0);
                                FrameReader.Reset();
                                logger.Trace("收到持续数据帧:{0} {1} {2}", SessionID, EndPoint, FrameReader.ToString());
                            }
                        }
                    }
                }
                catch
                {
                    break;
                }
            }



            if (!isClosed)
            {
                Protocol.TryGetCommand(this);
            }
        }
예제 #3
0
        private void ProcessState(object obj)
        {
            Socket         socket  = (Socket)obj;
            NetworkChannel channel = null;

            JsonAction action   = JsonAction.None;
            JsonType   jsonType = JsonType.None;

            try
            {
                do
                {
                    // Connect
                    channel = new NetworkChannel(socket);

                    // Receive
                    HttpRequest httpRequest;
                    channel.Receive(out httpRequest);
                    if (httpRequest == null)
                    {
                        channel.SendBadRequest();
                        return;
                    }

                    // Data
                    Status = DemonStatus.Success;

                    // Handshake
                    if (httpRequest.Session == null)
                    {
                        ServerStatusComponent    status  = Owner.Get <ServerStatusComponent>();
                        HandshakeResponseCommand command = new HandshakeResponseCommand(Owner, socket)
                        {
                            Listener = status.Update
                        };
                        command.Execute(httpRequest);
                        break;
                    }

                    // Session
                    SessionMapComponent sessions = Owner.Get <SessionMapComponent>();
                    Entity entity = sessions.Get(httpRequest.Session);
                    if (entity == null)
                    {
                        channel.SendUnauthorized();
                        break;
                    }

                    // TODO: Version check
                    //
                    // Message
                    SessionComponent session            = entity.Get <SessionComponent>();
                    string           decrypted          = session.Decrypt(httpRequest.Data);
                    JsonPacket       jsonRequest        = JsonPacket.Parse(decrypted);
                    JsonMessage      jsonRequestMessage = JsonMessage.Parse(jsonRequest.Message);
                    jsonType = jsonRequestMessage.Type;

                    switch (jsonType)
                    {
                    case JsonType.Handshake:
                    {
                        HandshakeResponseCommand command = new HandshakeResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Ping:
                    {
                        PingResponseCommand command = new PingResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Info:
                    {
                        InfoResponseCommand command = new InfoResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Join:
                    {
                        JoinResponseCommand command = new JoinResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Tunnel:
                    {
                        TunnelResponseCommand command = new TunnelResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Search:
                    {
                        SearchResponseCommand command = new SearchResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Group:
                    {
                        GroupResponseCommand command = new GroupResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Browse:
                    {
                        BrowseResponseCommand command = new BrowseResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Download:
                    {
                        // TODO: Add max transfer check!
                        //
                        DownloadResponseCommand command = new DownloadResponseCommand(Owner, socket);
                        action = command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Upload:
                    {
                        UploadResponseCommand command = new UploadResponseCommand(Owner, socket);
                        action = command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Quit:
                    {
                        QuitResponseCommand command = new QuitResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    default:
                    {
                        channel.SendBadRequest();
                        return;
                    }
                    }
                }while (action != JsonAction.None);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Status = DemonStatus.Error;
                channel.SendInternalServerError();
            }
            finally
            {
                if (channel != null)
                {
                    channel.Shutdown();
                }

                if (jsonType != JsonType.Tunnel)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                }
            }
        }