protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
 {
     Log.ErrorFormat("Looking for Peer Id {0}", new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]));
     PhotonClientPeer peer;
     Server.ConnectionCollection<PhotonConnectionCollection>().Clients.TryGetValue(
         new Guid((Byte[]) message.Parameters[(byte) ClientParameterCode.PeerId]), out peer);
     if (peer != null)
     {
         Log.DebugFormat("Found Peer");
         message.Parameters.Remove((byte) ClientParameterCode.PeerId);
         var response = message as PhotonResponse;
         if (response != null)
         {
             peer.SendOperationResponse(new OperationResponse(response.Code, response.Parameters)
             {
                 DebugMessage = response.DebugMessage,
                 ReturnCode = response.ReturnCode
             }, new SendParameters());
         }
         else
         {
             peer.SendOperationResponse(new OperationResponse(message.Code, message.Parameters),
                 new SendParameters());
         }
     }
     return true;
 }
Beispiel #2
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var para = new Dictionary <byte, object>
            {
                { (byte)ClientParameterCode.PeerId, message.Parameters[(byte)ClientParameterCode.PeerId] },
                { (byte)ClientParameterCode.SubOperationCode, message.Parameters[(byte)ClientParameterCode.SubOperationCode] }
            };

            var operation = new PlayerMovementOperation(serverPeer.Protocol, message);

            //IF INCORRECT
            if (!operation.IsValid)
            {
                Log.ErrorFormat(operation.GetErrorMessage());
                serverPeer.SendOperationResponse(new OperationResponse(message.Code)
                {
                    ReturnCode   = (int)ErrorCode.OperationInvalid,
                    DebugMessage = operation.GetErrorMessage(),
                    Parameters   = para
                }, new SendParameters());
                return(true);
            }
            //WHEN CORRECT
            var instance       = Util.GetCPlayerInstance(Server, message);
            var playerMovement = ComplexServerCommon.SerializeUtil.Deserialize <PlayerMovement>(operation.PlayerMovement);

            //implement movement logic

            return(true);
        }
Beispiel #3
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var para = new Dictionary <byte, object>()
            {
                { (byte)ClientParameterCode.PeerId, message.Parameters[(byte)ClientParameterCode.PeerId] },
                { (byte)ClientParameterCode.SubOperationCode, MessageSubCode.PullQueue },
            };

            var operation = new CreateQueueOperation(serverPeer.Protocol, message);

            if (!operation.IsValid)
            {
                serverPeer.SendOperationResponse(new OperationResponse
                                                     (message.Code, para)
                {
                    ReturnCode = (int)ErrorCode.OperationInvalid, DebugMessage = "Create queue operation invalid"
                }, new SendParameters());
            }

            var instance = Util.GetCPlayerInstance(Server, message);

            var queueItemRequest = SerializeUtil.Deserialize <FightQueueListItem>(operation.fightInit);

            queueItemRequest.Creator = instance.Name;

            Fight newFight           = instance.CurrentFight;
            bool  wasAllowedNewFight = false;

            if (instance.CurrentFight == null)
            {
                newFight           = _fightManager.AddFight(queueItemRequest);
                wasAllowedNewFight = newFight.addPlayer(1, instance);                 //1 - red, 2 - blue teams
//			    IEffect effect = EffectCache.GetEffect(EffectEnum.INJURY);
//                Log.DebugFormat("Fetched effect of type: {0}", effect.GetType());
//                instance.Effects.Apply(effect);
            }

            //send response with refreshed queue list

            if (wasAllowedNewFight)
            {
                instance.SendPacket(new PulledQueuesPacket(_fightManager));
                foreach (var player in newFight.getPlayers.Values)
                {
                    player.SendPacket(new FightQueueParticipantsPacket(newFight));
                    Log.Debug(CLASSNAME + " - OnHandleMessage:: sending queue info back to client");
                }
            }
            else
            {
                serverPeer.SendOperationResponse(new OperationResponse(message.Code)
                {
                    ReturnCode   = (int)ErrorCode.AlreadyInFight,
                    DebugMessage = "Already queued/engaged in a fight",
                    Parameters   = para,
                }, new SendParameters());
                Log.Debug(CLASSNAME + " - OnHandleMessage:: was not allowed a new fight");
            }
            return(true);
        }
Beispiel #4
0
        public override void Connect(PhotonServerPeer serverPeer)
        {
            if ((serverPeer.ServerType & (int)ServerType.Region) != 0)
            {
                Dictionary <byte, object> parameters = new Dictionary <byte, object>();

                Dictionary <string, string> serverList = Servers.Where(
                    incomingSubServerPeer =>
                    incomingSubServerPeer.Value.ServerId.HasValue &&
                    !incomingSubServerPeer.Value.ServerId.Equals(serverPeer.ServerId) &&
                    (incomingSubServerPeer.Value.ServerType & (int)ServerType.Region) != 0)
                                                         .ToDictionary(
                    incomingSubServerPeer => incomingSubServerPeer.Value.ApplicationName,
                    incomingSubServerPeer => incomingSubServerPeer.Value.TcpAddress);

                if (serverList.Count > 0)
                {
                    if (Log.IsDebugEnabled)
                    {
                        Log.DebugFormat("Sending list of {0} connected sub servers", serverList.Count);
                    }
                    parameters.Add((byte)ServerParameterCode.SubServerDictionary, serverList);
                    serverPeer.SendEvent(new EventData((byte)ServerEventCode.SubServerList, parameters), new SendParameters());
                }
            }
        }
Beispiel #5
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            int  characterId = Convert.ToInt32(message.Parameters[(byte)ClientParameterCode.CharacterId]);
            Guid peerId      = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);

            try
            {
                var clients = Server.ConnectionCollection <SubServerConnectionCollection>().Clients;
                clients.Add(peerId, _clientFactory(peerId));
                var instance = clients[peerId].ClientData <CPlayerInstance>();

                instance.UserID      = Convert.ToInt32(message.Parameters[(byte)ClientParameterCode.UserId]);
                instance.ServerPeer  = serverPeer;
                instance.Client      = clients[peerId];
                instance.CharacterID = characterId;
                instance.ObjectId    = characterId;

                instance.Restore();
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
            return(true);
        }
 public override PhotonServerPeer OnGetSeverByType(int serverType)
 {
     PhotonServerPeer server = null;
     switch ((ServerType) Enum.ToObject(typeof (ServerType), serverType))
     {
         case ServerType.Login:
             if (LoginServer != null)
             {
                 Log.DebugFormat("Found login server");
                 server = LoginServer;
             }
             else
             {
                 Log.DebugFormat("Login server does not exist in collection!");
             }
             break;
         case ServerType.Chat:
             if (ChatServer != null)
             {
                 Log.DebugFormat("Found Chat Server");
                 server = ChatServer;
             }
             break;
         default:
             Log.DebugFormat("oh shit this server type is f****d up");
             break;
     }
     return server;
 }
Beispiel #7
0
        public override PhotonServerPeer OnGetServerByType(int serverType)
        {
            PhotonServerPeer server = null;

            switch ((ServerType)Enum.ToObject(typeof(ServerType), serverType))
            {
            case ServerType.Login:
                if (LoginServer != null)
                {
                    //Log.DebugFormat("Found Login Server");
                    server = LoginServer;
                }
                break;

            case ServerType.Chat:
                if (ChatServer != null)
                {
                    //Log.DebugFormat("Found Chat Server");
                    server = ChatServer;
                }
                break;

            case ServerType.Region:
                if (RegionServer != null)
                {
                    //Log.DebugFormat("Found Region Server");
                    server = RegionServer;
                }
                break;
            }
            return(server);
        }
Beispiel #8
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.ErrorFormat("Looking for Peer Id {0}", new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]));
            PhotonClientPeer peer;

            Server.ConnectionCollection <PhotonConnectionCollection>().Clients.TryGetValue(
                new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]), out peer);
            if (peer != null)
            {
                Log.DebugFormat("Found Peer");
                message.Parameters.Remove((byte)ClientParameterCode.PeerId);
                var response = message as PhotonResponse;
                if (response != null)
                {
                    peer.SendOperationResponse(new OperationResponse(response.Code, response.Parameters)
                    {
                        DebugMessage = response.DebugMessage,
                        ReturnCode   = response.ReturnCode
                    }, new SendParameters());
                }
                else
                {
                    peer.SendOperationResponse(new OperationResponse(message.Code, message.Parameters),
                                               new SendParameters());
                }
            }
            return(true);
        }
Beispiel #9
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var para = new Dictionary <byte, object>()
            {
                { (byte)ClientParameterCode.PeerId, message.Parameters[(byte)ClientParameterCode.PeerId] },
                { (byte)ClientParameterCode.SubOperationCode, MessageSubCode.PullQueue },
            };

            var instance = Util.GetCPlayerInstance(Server, message);
            var fight    = instance.CurrentFight;
            var success  = _fightManager.LeaveQueue(instance);

            if (success)
            {
                instance.SendPacket(new PulledQueuesPacket(_fightManager));
                if (fight != null)
                {
                    var fightParticipants = new FightQueueParticipantsPacket(fight);
                    foreach (var player in fight.getPlayers.Values)
                    {
                        player.SendPacket(new PulledQueuesPacket(_fightManager));
                        player.SendPacket(fightParticipants);
                    }
                }
            }
            else
            {
                serverPeer.SendOperationResponse(new OperationResponse(message.Code)
                {
                    ReturnCode = (int)ErrorCode.OperationInvalid, DebugMessage = "Cannot leave this queue", Parameters = para
                }, new SendParameters());
            }
            return(true);
        }
 public PhotonPeerFactory(PhotonServerPeer.Factory serverPeerFactory, PhotonClientPeer.Factory clientPeerFactory, PhotonConnectionCollection subServerCollection, PhotonApplication application)
 {
     _serverPeerFactory = serverPeerFactory;
     _clientPeerFactory = clientPeerFactory;
     _subServerCollection = subServerCollection;
     _application = application;
 }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            int characterId = Convert.ToInt32(message.Parameters[(byte) ClientParameterCode.CharacterId]);
            Guid peerId = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);
            Log.DebugFormat("character {0} peer {1}", characterId, peerId);
            try
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var character =
                            session.QueryOver<ComplexCharacter>()
                                .Where(cc => cc.Id == characterId)
                                .List()
                                .FirstOrDefault();

                        transaction.Commit();
                        var clients = Server.ConnectionCollection<SubServerConnectionCollection>().Clients;
                        clients.Add(peerId, _clientFactory());
                        // TODO Add character data to the cl;ient list for chat
                        clients[peerId].ClientData<CharacterData>().CharacterId = character.Id;
                        clients[peerId].ClientData<CharacterData>().UserId = Convert.ToInt32(message.Parameters[(byte) ClientParameterCode.UserId]);

                        //Notify guild members that someone logged in
                        //Notify friends list that someone logged in
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            return true;
        }
Beispiel #12
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            if (message.Parameters.ContainsKey((byte)ClientParameterCode.PeerId))
            {
                PhotonClientPeer peer;
                Server.ConnectionCollection <ComplexConnectionCollection>().Clients.TryGetValue(
                    new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]), out peer);
                if (peer != null)
                {
                    int characterId = Convert.ToInt32(message.Parameters[(byte)ClientParameterCode.CharacterId]);
                    peer.ClientData <CharacterData>().CharacterId = characterId;

                    var para = new Dictionary <byte, object>
                    {
                        { (byte)ClientParameterCode.CharacterId, characterId },
                        { (byte)ClientParameterCode.PeerId, message.Parameters[(byte)ClientParameterCode.PeerId] },
                        { (byte)ClientParameterCode.UserId, peer.ClientData <CharacterData>().UserId }
                    };
                    //Register client with CHAT Server
                    var chatServer = Server.ConnectionCollection <ComplexConnectionCollection>().OnGetServerByType((int)ServerType.Chat);
                    if (chatServer != null)
                    {
                        chatServer.SendEvent(new EventData((byte)ServerEventCode.CharacterRegister)
                        {
                            Parameters = para
                        }, new SendParameters());
                    }

                    //Register client with REGION Server
                    var regionServer = Server.ConnectionCollection <ComplexConnectionCollection>().OnGetServerByType((int)ServerType.Region);
                    if (chatServer != null)
                    {
                        peer.CurrentServer = regionServer;
                        regionServer.SendEvent(new EventData((byte)ServerEventCode.CharacterRegister)
                        {
                            Parameters = para
                        }, new SendParameters());
                    }

                    message.Parameters.Remove((byte)ClientParameterCode.PeerId);
                    message.Parameters.Remove((byte)ClientParameterCode.UserId);
                    message.Parameters.Remove((byte)ClientParameterCode.CharacterId);

                    var response = message as PhotonResponse;
                    if (response != null)
                    {
                        peer.SendOperationResponse(new OperationResponse(response.Code, response.Parameters)
                        {
                            ReturnCode = response.ReturnCode, DebugMessage = response.DebugMessage
                        }, new SendParameters());
                    }
                    else
                    {
                        peer.SendOperationResponse(new OperationResponse(message.Code, message.Parameters), new SendParameters());
                    }
                }
            }
            return(true);
        }
 protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
 {
     Guid peerId = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);
     //TODO remove from groups? guilds etc.
     Server.ConnectionCollection<SubServerConnectionCollection>().Clients.Remove(peerId);
     Log.DebugFormat("Removed peer {0}, now we have {1} clients",peerId, Server.ConnectionCollection<SubServerConnectionCollection>().Clients.Count);
     return true;
 }
Beispiel #14
0
        public override void ResetServers()
        {
            if (ChatServer != null && ChatServer.ServerType != (int)ServerType.Chat)
            {
                PhotonServerPeer peer = Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int)ServerType.Chat).FirstOrDefault();
                if (peer != null)
                {
                    ChatServer = peer;
                }
            }
            if (LoginServer != null && LoginServer.ServerType != (int)ServerType.Login)
            {
                PhotonServerPeer peer = Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int)ServerType.Login).FirstOrDefault();
                if (peer != null)
                {
                    LoginServer = peer;
                }
            }
            if (RegionServer != null && RegionServer.ServerType != (int)ServerType.Region)
            {
                PhotonServerPeer peer = Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int)ServerType.Region).FirstOrDefault();
                if (peer != null)
                {
                    RegionServer = peer;
                }
            }

            if (ChatServer == null || ChatServer.ServerId == null)
            {
                ChatServer =
                    Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int)ServerType.Chat).FirstOrDefault() ??
                    Servers.Values.Where(subServerPeer => (subServerPeer.ServerType & (int)ServerType.Chat) != 0).FirstOrDefault();
            }
            if (LoginServer == null || LoginServer.ServerId == null)
            {
                LoginServer =
                    Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int)ServerType.Login).FirstOrDefault() ??
                    Servers.Values.Where(subServerPeer => (subServerPeer.ServerType & (int)ServerType.Login) != 0).FirstOrDefault();
            }
            if (RegionServer == null || RegionServer.ServerId == null)
            {
                RegionServer =
                    Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int)ServerType.Region).FirstOrDefault() ??
                    Servers.Values.Where(subServerPeer => (subServerPeer.ServerType & (int)ServerType.Region) != 0).FirstOrDefault();
            }
            if (ChatServer != null)
            {
                Log.DebugFormat("Chat Server: {0}", ChatServer.ConnectionId);
            }
            if (LoginServer != null)
            {
                Log.DebugFormat("Login Server: {0}", LoginServer.ConnectionId);
            }
            if (RegionServer != null)
            {
                Log.DebugFormat("Region Server: {0}", RegionServer.ConnectionId);
            }
        }
Beispiel #15
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var instance = Util.GetCPlayerInstance(Server, message);

            //send battleinfo to player for UI update
            instance.SendPacket(new UserFightInfoUpdatePacket(instance));
            instance.SendPacket(new FightParticipantsPacket(instance, false));
            return(true);
        }
Beispiel #16
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Guid peerId = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);

            //TODO remove from groups? guilds etc.
            Server.ConnectionCollection <SubServerConnectionCollection>().Clients.Remove(peerId);
            Log.DebugFormat("Removed peer {0}, now we have {1} clients", peerId, Server.ConnectionCollection <SubServerConnectionCollection>().Clients.Count);
            return(true);
        }
Beispiel #17
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            OperationResponse operationResponse;

            if (serverPeer.ServerId.HasValue)
            {
                operationResponse = new OperationResponse(message.Code)
                {
                    ReturnCode = -1, DebugMessage = "Already Registered"
                };
            }
            else
            {
                var registerRequest = new RegisterSubServer(serverPeer.Protocol, message);
                if (!registerRequest.IsValid)
                {
                    string msg = registerRequest.GetErrorMessage();
                    if (Log.IsDebugEnabled)
                    {
                        Log.DebugFormat("Invalid Register Request: {0}", msg);
                    }

                    operationResponse = new OperationResponse(message.Code)
                    {
                        DebugMessage = msg, ReturnCode = (short)ErrorCode.OperationInvalid
                    };
                }
                else
                {
                    var registerData = SerializeUtil.Deserialize <RegisterSubServerData>(registerRequest.RegisterSubServerOperation);
                    if (Log.IsDebugEnabled)
                    {
                        Log.DebugFormat("Received register request: Address={0}, UdpPort={2}, TcpPort={1}, Type={3}",
                                        registerData.GameServerAddress, registerData.TcpPort, registerData.UdpPort, registerData.ServerType);
                    }
                    if (registerData.UdpPort.HasValue)
                    {
                        serverPeer.UdpAddress = registerData.GameServerAddress + ":" + registerData.UdpPort;
                    }
                    if (registerData.TcpPort.HasValue)
                    {
                        serverPeer.TcpAddress = registerData.GameServerAddress + ":" + registerData.TcpPort;
                    }
                    serverPeer.ServerId   = registerData.ServerId;
                    serverPeer.ServerType = registerData.ServerType;

                    serverPeer.ApplicationName = registerData.ApplicationName;
                    Server.ConnectionCollection <PhotonConnectionCollection>().OnConnect(serverPeer);
                    operationResponse = new OperationResponse(message.Code);
                }
            }
            serverPeer.SendOperationResponse(operationResponse, new SendParameters());
//			string FilePath = Path.Combine(Server.BinaryPath, "esquel.dar");
//			List<string> sqlsetup = File.ReadLines(FilePath).ToList();
//			Log.DebugFormat("{0}\n{1}\n{2}\n{3}", sqlsetup[0],sqlsetup[1],sqlsetup[1],sqlsetup[1]);
            return(true);
        }
Beispiel #18
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var instance = Util.GetCPlayerInstance(Server, message);

            instance.CurrentFight.SetPlayerReady(instance.ObjectId, (bool)message.Parameters[(byte)ClientParameterCode.Object]);

            //send this players "Ready" to other queue participants

            return(true);
        }
 //TODO fix me!! this wont catch and we cant see when someone logs out
 protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
 {
     Log.DebugFormat("Handling User Logged Out Message");
     LoginServer server = Server as LoginServer;
     if (server != null)
     {
         Guid peerId = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);
         server.ConnectionCollection<SubServerConnectionCollection>().Clients.Remove(peerId);
     }
     return true;
 }
Beispiel #20
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.DebugFormat("Handling User Logged Out Message");
            LoginServer server = Server as LoginServer;

            if (server != null)
            {
                Guid peerId = new Guid((byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);
                server.ConnectionCollection <SubServerConnectionCollection>().Clients.Remove(peerId);
            }
            return(true);
        }
Beispiel #21
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Guid peerId = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);
            // remove from Groups, Guilds, etc.
            var clients = Server.ConnectionCollection <SubServerConnectionCollection>().Clients;

            clients[peerId].ClientData <CPlayerInstance>().DeleteMe();

            Server.ConnectionCollection <SubServerConnectionCollection>().Clients.Remove(peerId);
            Log.DebugFormat("Removed Peer {0} from Region, cleaneup and stored the character, now we have {1} clients.", peerId, Server.ConnectionCollection <SubServerConnectionCollection>().Clients.Count);
            return(true);
        }
Beispiel #22
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var peerId = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);

            LoginServer login = Server as LoginServer;

            if (login != null)
            {
                login.ConnectionCollection <SubServerConnectionCollection>().Clients.Remove(peerId);
            }

            return(true);
        }
Beispiel #23
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var instance = Util.GetCPlayerInstance(Server, message);

            instance.Spawn();
            instance.BroadcastUserInfo();

            Log.DebugFormat("Character {0} joined Region Server.", instance.Name);
            //Notify guild members that someone logged in

            //Notify friend list that someone logged in
            return(true);
        }
 public override void Disconnect(PhotonServerPeer serverPeer)
 {
     if (serverPeer.ServerId.HasValue)
     {
         if (ChatServer != null && serverPeer.ServerId.Value == ChatServer.ServerId)
         {
             ChatServer = null;
         }
         if (LoginServer != null && serverPeer.ServerId.Value == LoginServer.ServerId)
         {
             LoginServer = null;
         }
     }
 }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            if (message.Parameters.ContainsKey((byte) ClientParameterCode.PeerId))
            {
                PhotonClientPeer peer;
                Server.ConnectionCollection<ComplexConnectionCollection>()
                    .Clients.TryGetValue(new Guid((Byte[]) message.Parameters[(byte) ClientParameterCode.PeerId]),
                        out peer);
                if (peer != null)
                {
                    int characterId = Convert.ToInt32(message.Parameters[(byte) ClientParameterCode.CharacterId]);
                    peer.ClientData<CharacterData>().CharacterId = characterId;

                    var para = new Dictionary<byte, object>
                    {
                        {(byte) ClientParameterCode.CharacterId, characterId},
                        {(byte) ClientParameterCode.PeerId, new Guid((Byte[]) message.Parameters[(byte) ClientParameterCode.PeerId]).ToByteArray()},
                        {(byte)ClientParameterCode.UserId, peer.ClientData<CharacterData>().UserId}
                    };
                    var chatServer = Server.ConnectionCollection<ComplexConnectionCollection>().OnGetSeverByType((int) ServerType.Chat);
                    if (chatServer != null)
                    {
                        chatServer.SendEvent(new EventData((byte) ServerEventCode.CharacterRegister) {Parameters = para},new SendParameters());
                    }
                    //TODO add code to send same event to Region server

                    message.Parameters.Remove((byte) ClientParameterCode.PeerId);
                    message.Parameters.Remove((byte) ClientParameterCode.UserId);
                    message.Parameters.Remove((byte) ClientParameterCode.CharacterId);

                    var response = message as PhotonResponse;
                    if (response != null)
                    {
                        peer.SendOperationResponse(
                            new OperationResponse(response.Code, response.Parameters)
                            {
                                DebugMessage = response.DebugMessage,
                                ReturnCode = response.ReturnCode
                            }, new SendParameters());

                    }
                    else
                    {
                        peer.SendOperationResponse(new OperationResponse(message.Code, message.Parameters),
                            new SendParameters());
                    }
                }
            }
            return true;
        }
Beispiel #26
0
 protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
 {
     if (message.Parameters.ContainsKey((byte)ClientParameterCode.PeerId))
     {
         PhotonClientPeer peer;
         Server.ConnectionCollection <PhotonConnectionCollection>().Clients.TryGetValue(new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]), out peer);
         if (peer != null)
         {
             message.Parameters.Remove((byte)ClientParameterCode.PeerId);
             peer.SendEvent(new EventData(message.Code, message.Parameters), new SendParameters());
         }
     }
     return(true);
 }
Beispiel #27
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
//			var para = new Dictionary<byte, object>()
//			{
//				{(byte)ClientParameterCode.PeerId, message.Parameters[(byte)ClientParameterCode.PeerId]},
//			};
//
            var  instance = Util.GetCPlayerInstance(Server, message);
            Guid fightId  = Guid.Parse((string)message.Parameters[(byte)ClientParameterCode.FightID]);

            Fight fight = _fightManager.GetFight(fightId) as Fight;

            fight.addPlayer(instance);
            return(true);
        }
Beispiel #28
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var para = new Dictionary <byte, object>()
            {
                { (byte)ClientParameterCode.PeerId, message.Parameters[(byte)ClientParameterCode.PeerId] },
                { (byte)ClientParameterCode.SubOperationCode, message.Parameters[(byte)ClientParameterCode.SubOperationCode] },
                { (byte)ClientParameterCode.Object, SerializeUtil.Serialize(_fightManager.GetAllQueues()) },
            };

            serverPeer.SendEvent(new EventData(message.Code)
            {
                Parameters = para
            }, new SendParameters());

            return(true);
        }
Beispiel #29
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            if (!message.Parameters.ContainsKey((byte)ClientParameterCode.Object))
            {
                DebugUtils.Logp(DebugUtils.Level.ERROR, CLASSNAME, "OnHandleMessage", "No StatAllocationData object passed. Exiting handler.");
                return(true);
            }

            var para = new Dictionary <byte, object>
            {
                { (byte)ClientParameterCode.PeerId, message.Parameters[(byte)ClientParameterCode.PeerId] },
                { (byte)ClientParameterCode.SubOperationCode, message.Parameters[(byte)ClientParameterCode.SubOperationCode] }
            };

            var instance = Util.GetCPlayerInstance(Server, message);

            var statAllocData = SerializeUtil.Deserialize <StatAllocationData>(message.Parameters[(byte)ClientParameterCode.Object]);

            if (statAllocData.ResetPoints)
            {
                resetAllAllocatedStatPoints(instance);
            }
            else
            {
                foreach (var stat in statAllocData.Allocations)
                {
                    ((StatHolder)instance.Stats).SetStatByID(stat.Key, stat.Value);
                    instance.GetCharData <GeneralStats>().TotalAllocatedStats += stat.Value;
                    instance.Stats.AddToStat <StatPoints>(-stat.Value);
                }
            }

            var debugMessage = statAllocData.ResetPoints ? "Stats successfully reset!" : "Stats successfully added!";

            para.Add((byte)ClientParameterCode.Object, SerializeUtil.Serialize(instance.Stats.GetMainStatsForEnemy()));
            para.Add((byte)ClientParameterCode.StatsToAllocate, instance.Stats.GetStat <StatPoints>());

            serverPeer.SendOperationResponse(new OperationResponse(message.Code)
            {
                ReturnCode   = (int)ErrorCode.OK,
                DebugMessage = debugMessage,
                Parameters   = para
            }, new SendParameters());
            return(true);
        }
Beispiel #30
0
        /** Handles character login event from Proxy server.
         * Receives peerId and characterId in the message, queries character info in DB.
         * Then instantiates and adds character object to Clients dictionary and populates character info fields.
         * Fields are later used by chat message handlers to have additional information.
         *
         * TODO: Notifies friends/guild members that character is online
         */

        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var characterId = Convert.ToInt32(message.Parameters[(byte)ClientParameterCode.CharacterId]);
            var peerId      = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);

            try
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var character = session.QueryOver <ComplexCharacter>().Where(cc => cc.Id == characterId).List().FirstOrDefault();
                        if (character != null)
                        {
                            transaction.Commit();
                            var clients = Server.ConnectionCollection <SubServerConnectionCollection>().Clients;
                            clients.Add(peerId, _clientFactory(peerId));

                            //TODO: add character data to the client list for chat

                            clients[peerId].ClientData <CharacterData>().CharacterId = characterId;
                            clients[peerId].ClientData <CharacterData>().UserId      = Convert.ToInt32(message.Parameters[(byte)ClientParameterCode.UserId]);
                            clients[peerId].ClientData <ChatPlayer>().CharacterName  = character.Name;
                            clients[peerId].ClientData <ServerData>().ServerPeer     = serverPeer;

                            Log.DebugFormat("Character {0} in chat server.", character.Name);

                            //Notify guild members that someone logged in
                            //Notify friend list that someone logged in
                        }
                        else
                        {
                            transaction.Commit();
                            throw new SqlParseException(CLASSNAME + " Character not found in database");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e.StackTrace);
                throw;
            }
            return(true);
        }
Beispiel #31
0
        public override void Register(PhotonServerPeer peer)
        {
            var registerSubServerOperation =
                new RegisterSubServerData()
            {
                GameServerAddress = PublicIpAddress.ToString(),
                TcpPort           = TcpPort,
                UdpPort           = UdpPort,
                ServerId          = ServerId,
                ServerType        = ServerType,
                ApplicationName   = ApplicationName
            };

            peer.SendOperationRequest(new OperationRequest((byte)ServerOperationCode.RegisterSubServer,
                                                           new RegisterSubServer()
            {
                RegisterSubServerOperation = SerializeUtil.Serialize(registerSubServerOperation)
            }), new SendParameters());
        }
Beispiel #32
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.DebugFormat("receiving equipItem request");

            var operation = new ItemEquipOperation(serverPeer.Protocol, message);

            if (!operation.IsValid)
            {
                Log.DebugFormat("Invalid operation for Equip Item");
            }

            var instance = Util.GetCPlayerInstance(Server, message);
            var items    = instance.Items;

            items.EquipItem(operation.InventorySlot);
            instance.Stats.RefreshCurrentHealth();
            instance.BroadcastUserInfo();

            return(true);
        }
Beispiel #33
0
        public override void Register(PhotonServerPeer peer)
        {
            var registerSubServerOperation = new RegisterSubServerData()
            {
                GameServerAddress = PublicIpAddress.ToString(),
                TcpPort = TcpPort,
                UdpPort = UdpPort,
                ServerId = ServerId,
                ServerType = ServerType,
                ApplicationName = ApplicationName

            };
            XmlSerializer mySerializer = new XmlSerializer(typeof(RegisterSubServerData));
            StringWriter outString = new StringWriter();
            mySerializer.Serialize(outString, registerSubServerOperation);

            peer.SendOperationRequest(
                new OperationRequest((byte)ServerOperationCode.RegisterSubServer,
                    new RegisterSubServer() { RegisterSubServerOperation = outString.ToString() }), new SendParameters());
        }
Beispiel #34
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.DebugFormat("LoginResponseHandler.OnHandleMessage with code {0}", message.Code);
            if (message.Parameters.ContainsKey((byte)ClientParameterCode.PeerId))
            {
                PhotonClientPeer peer;
                Server.ConnectionCollection <PhotonConnectionCollection>().Clients.TryGetValue(
                    new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]), out peer);

                if (peer != null)
                {
                    //puts userid into characterData so we dont worry about what their name and shit is
                    if (message.Parameters.ContainsKey((byte)ClientParameterCode.UserId))
                    {
                        Log.DebugFormat("Found user {0}", Convert.ToInt32(message.Parameters[(byte)ClientParameterCode.UserId]));
                        peer.ClientData <CharacterData>().UserId = Convert.ToInt32(message.Parameters[(byte)ClientParameterCode.UserId]);
                    }

                    message.Parameters.Remove((byte)ClientParameterCode.PeerId);
                    message.Parameters.Remove((byte)ClientParameterCode.CharacterId);
                    message.Parameters.Remove((byte)ClientParameterCode.UserId);

                    var response = message as PhotonResponse;
                    if (response != null)
                    {
                        peer.SendOperationResponse(new OperationResponse(response.Code, response.Parameters)
                        {
                            DebugMessage = response.DebugMessage,
                            ReturnCode   = response.ReturnCode
                        }, new SendParameters());
                    }
                    else
                    {
                        peer.SendOperationResponse(new OperationResponse(message.Code, message.Parameters),
                                                   new SendParameters());
                    }
                }
            }
            return(true);
        }
Beispiel #35
0
        /** Receives forwarded message from client with chat input object,
         *  parses the message (verifies character fields) and sends the textmessage out to each client connected to chat server
         *
         *  Will be parsed differently based on type of the chat message (General, Whisper, Guild, etc..)
         */

        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            if (message.Parameters.ContainsKey((byte)ClientParameterCode.Object))
            {
                Guid peerId   = new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId]);
                var  chatItem = SerializeUtil.Deserialize <ChatItem>(message.Parameters[(byte)ClientParameterCode.Object]);

                switch (chatItem.Type)
                {
                case (ChatType.General):
                    chatItem.ByPlayer = Server.ConnectionCollection <SubServerConnectionCollection>().Clients[peerId].ClientData <ChatPlayer>().CharacterName;
                    //chatItem.Text - contains client's input string;

                    foreach (var client in Server.ConnectionCollection <SubServerConnectionCollection>().Clients)
                    {
                        var para = new Dictionary <byte, object>()
                        {
                            { (byte)ClientParameterCode.PeerId, client.Key.ToByteArray() },
                            { (byte)ClientParameterCode.Object, SerializeUtil.Serialize(chatItem) }
                        };
                        var eventData = new EventData {
                            Code = (byte)ClientEventCode.Chat, Parameters = para
                        };

                        client.Value.ClientData <ServerData>().ServerPeer.SendEvent(eventData, new SendParameters());
                    }
                    break;

                case (ChatType.Whisper):
                    break;

                case (ChatType.Guild):
                    break;

                default:
                    break;
                }
            }
            return(true);
        }
Beispiel #36
0
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var instance = Util.GetCPlayerInstance(Server, message);
            var itemId   = Convert.ToInt32(message.Parameters[(byte)ClientParameterCode.ObjectId]);

            var item = instance.Items.UseItem(itemId) as Item;

            if (item.Effect == null)
            {
                serverPeer.SendOperationResponse(new OperationResponse(message.Code, new Dictionary <byte, object> {
                    { (byte)ClientParameterCode.PeerId, message.Parameters[(byte)ClientParameterCode.PeerId] }
                })
                {
                    ReturnCode   = (int)ErrorCode.OperationInvalid,
                    DebugMessage = "Item cannot be used"
                }, new SendParameters());

                return(true);
            }

            if (item != null)
            {
                switch (item.Effect.Type)
                {
                case EffectType.STATONLY:
                    instance.SendPacket(new UserInfoUpdatePacket(instance));
                    break;

                case EffectType.ONHIT:
                    break;

                case EffectType.MISC:
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            return(true);
        }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.DebugFormat("LoginResponseHandler.OnHandleMessage with code {0}", message.Code);
            if (message.Parameters.ContainsKey((byte) ClientParameterCode.PeerId))
            {
                PhotonClientPeer peer;
                Server.ConnectionCollection<PhotonConnectionCollection>().Clients.TryGetValue(
                    new Guid((Byte[]) message.Parameters[(byte) ClientParameterCode.PeerId]), out peer);

                if (peer != null)
                {
                    //puts userid into characterData so we dont worry about what their name and shit is
                    if (message.Parameters.ContainsKey((byte) ClientParameterCode.UserId))
                    {
                        Log.DebugFormat("Found user {0}",Convert.ToInt32(message.Parameters[(byte) ClientParameterCode.UserId]));
                        peer.ClientData<CharacterData>().UserId = Convert.ToInt32(message.Parameters[(byte) ClientParameterCode.UserId]);
                    }

                    message.Parameters.Remove((byte) ClientParameterCode.PeerId);
                    message.Parameters.Remove((byte) ClientParameterCode.CharacterId);
                    message.Parameters.Remove((byte) ClientParameterCode.UserId);

                    var response = message as PhotonResponse;
                    if (response != null)
                    {
                        peer.SendOperationResponse(new OperationResponse(response.Code, response.Parameters)
                        {
                            DebugMessage = response.DebugMessage,
                            ReturnCode = response.ReturnCode
                        }, new SendParameters());
                    }
                    else
                    {
                        peer.SendOperationResponse(new OperationResponse(message.Code, message.Parameters),
                            new SendParameters());
                    }
                }
            }
            return true;
        }
Beispiel #38
0
        public void Register(PhotonServerPeer peer)
        {
            var registerSubServerOperation = new RegisterSubServerData()
            {
                GameServerAddress = ServerConfiguration.PublicIpAddress,
                TcpPort           = ServerConfiguration.TcpPort,
                UdpPort           = ServerConfiguration.UdpPort,
                ServerId          = ServerConfiguration.ServerId,
                ServerType        = ServerConfiguration.ServerType,
                ServerName        = ServerConfiguration.ServerName
            };

            XmlSerializer mySerializer = new XmlSerializer(typeof(RegisterSubServerData));
            StringWriter  outString    = new StringWriter();

            mySerializer.Serialize(outString, registerSubServerOperation);

            peer.SendOperationRequest(new OperationRequest(0, new RegisterSubServer()
            {
                RegisterSubServerOperation = outString.ToString()
            }), new SendParameters());
        }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.DebugFormat("On handle message called in handleserverregistration");
            OperationResponse operationResponse;
            if (serverPeer.ServerId.HasValue)
            {
                Log.DebugFormat("REGISTRATION EXISTS");
                operationResponse = new OperationResponse(message.Code)
                {
                    ReturnCode = -1,
                    DebugMessage = "Already registered."
                };
            }
            else
            {
                var registerRequest = new RegisterSubServer(serverPeer.Protocol, message);
                if (!registerRequest.IsValid)
                {
                    Log.DebugFormat("REGISTRATION NOT VALID");
                    string msg = registerRequest.GetErrorMessage();
                    if (Log.IsDebugEnabled)
                    {
                        Log.DebugFormat("invalid register request {0}", msg);
                    }

                    operationResponse = new OperationResponse(message.Code)
                    {
                        DebugMessage = msg,
                        ReturnCode = (short) ErrorCode.OperationInvalid
                    };
                }
                else
                {
                    Log.DebugFormat("REGISTRATION VALID");

                    XmlSerializer mySerializer = new XmlSerializer(typeof(RegisterSubServerData));
                    StringReader inStream = new StringReader(registerRequest.RegisterSubServerOperation);
                    var registerData = (RegisterSubServerData)mySerializer.Deserialize(inStream);

                    if (Log.IsDebugEnabled)
                    {

                        Log.DebugFormat("Received register request: Address={0}, udptport={2}, tcport={1}, Type={3}",
                            registerData.GameServerAddress, registerData.TcpPort, registerData.UdpPort, registerData.ServerType);
                    }
                    if (registerData.UdpPort.HasValue)
                    {
                        serverPeer.UdpAddress = registerData.GameServerAddress + ":" + registerData.UdpPort;
                    }
                    if (registerData.TcpPort.HasValue)
                    {
                        serverPeer.TcpAddress = registerData.GameServerAddress + ":" + registerData.UdpPort;
                    }

                    serverPeer.ServerId = registerData.ServerId;
                    serverPeer.ServerType = registerData.ServerType;
                    serverPeer.ApplicationName = registerData.ApplicationName;
                    Server.ConnectionCollection<PhotonConnectionCollection>().OnConnect(serverPeer);
                    operationResponse = new OperationResponse(message.Code);
                }
            }
            serverPeer.SendOperationResponse(operationResponse, new SendParameters());
            return true;
        }
 protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
 {
     Log.ErrorFormat("No existing request Handler. {0} - {1}", message.Code, message.SubCode);
     return true;
 }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var operation = new ListCharacters(serverPeer.Protocol, message);
            if (!operation.IsValid)
            {
                Log.DebugFormat("operation is invalid");
                Log.DebugFormat("Invalid Operation - {0}", operation.GetErrorMessage());
                serverPeer.SendOperationResponse(
                    new OperationResponse(message.Code)
                    {
                        ReturnCode = (int) ErrorCode.OperationInvalid,
                        DebugMessage = operation.GetErrorMessage()
                    }, new SendParameters());
                return true;
            }
            try
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var user =
                            session.QueryOver<User>().Where(u => u.Id == operation.UserId).List().FirstOrDefault();
                        if (user != null)
                        {
                            var profile =
                                session.QueryOver<UserProfile>().Where(up => up.UserId == user).List().FirstOrDefault();
                            if (profile != null)
                            {
                                var para = new Dictionary<byte, object>
                                {
                                    {(byte) ClientParameterCode.CharacterSlots, profile.CharacterSlots},
                                    {
                                        (byte) ClientParameterCode.PeerId,
                                        message.Parameters[(byte) ClientParameterCode.PeerId]
                                    },
                                    {
                                        (byte) ClientParameterCode.SubOperationCode,
                                        message.Parameters[(byte) ClientParameterCode.SubOperationCode]
                                    }
                                };
                                Log.DebugFormat("user id from operation is {0}", operation.UserId);
                                var characters =
                                    session.QueryOver<ComplexCharacter>().Where(cc => cc.UserId == user).List();
                                XmlSerializer characterSerializer = new XmlSerializer(typeof(CharacterListItem));

                                Hashtable characterList = new Hashtable();
                                Log.DebugFormat("characterlist count = {0}", characterList.Count);
                                foreach (var complexCharacter in characters)
                                {
                                    StringWriter outStream = new StringWriter();
                                    characterSerializer.Serialize(outStream, complexCharacter.BuilderCharacterListItem());
                                    characterList.Add(complexCharacter.Id, outStream.ToString());
                                }

                                para.Add((byte)ClientParameterCode.CharacterList, characterList);

                                transaction.Commit();

                                Log.DebugFormat("sending op response");
                                serverPeer.SendOperationResponse(
                                    new OperationResponse(message.Code, para) {ReturnCode = (byte) ErrorCode.Ok},
                                    new SendParameters());

            //                                serverPeer.SendOperationResponse(
                                //                                  new OperationResponse((byte) ClientOperationCode.Login) {Parameters = para},
                                //                                new SendParameters());
                            }
                            else
                            {
                                serverPeer.SendOperationResponse(
                                    new OperationResponse(message.Code)
                                    {
                                        ReturnCode = (int) ErrorCode.OperationInvalid,
                                        DebugMessage = "Profile not found"
                                    }, new SendParameters());
                            }
                        }
                        else
                        {
                            serverPeer.SendOperationResponse(
                                new OperationResponse(message.Code)
                                {
                                    ReturnCode = (int) ErrorCode.OperationInvalid,
                                    DebugMessage = "User not found"
                                }, new SendParameters());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                serverPeer.SendOperationResponse(
                    new OperationResponse(message.Code)
                    {
                        ReturnCode = (int) ErrorCode.OperationInvalid,
                        DebugMessage = e.ToString()
                    }, new SendParameters());
            }
            return true;
        }
 public abstract void Register(PhotonServerPeer peer);
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.DebugFormat("on handle in login server create character handler hit");
            var para = new Dictionary<byte, object>
            {
                {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]},
                {
                    (byte) ClientParameterCode.SubOperationCode,
                    message.Parameters[(byte) ClientParameterCode.SubOperationCode]
                }
            };
            var operation = new CreateCharacter(serverPeer.Protocol, message);
            if (!operation.IsValid)
            {
                Log.DebugFormat("operation invalid");
                serverPeer.SendOperationResponse(
                    new OperationResponse(message.Code)
                    {
                        ReturnCode = (int) ErrorCode.OperationInvalid,
                        DebugMessage = operation.GetErrorMessage(),
                        Parameters = para
                    }, new SendParameters());
                return true;
            }

            try
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var user =
                            session.QueryOver<User>().Where(u => u.Id == operation.UserId).List().FirstOrDefault();
                        var profile =
                            session.QueryOver<UserProfile>().Where(up => up.UserId == user).List().FirstOrDefault();
                        var characters = session.QueryOver<ComplexCharacter>().Where(cc => cc.UserId == user).List();
                        if (profile != null && profile.CharacterSlots <= characters.Count)
                        {
                            Log.DebugFormat("profile invalid or no slots");
                            serverPeer.SendOperationResponse(
                                new OperationResponse(message.Code)
                                {
                                    ReturnCode = (int) ErrorCode.InvalidCharacter,
                                    DebugMessage = "No free character slots",
                                    Parameters = para
                                }, new SendParameters());
                        }
                        else
                        {
                            var mySerializer = new XmlSerializer(typeof (CharacterCreateDetails));
                            var reader = new StringReader(operation.CharacterCreateDetails);
                            var createCharacter = (CharacterCreateDetails) mySerializer.Deserialize(reader);
                            var character =
                                session.QueryOver<ComplexCharacter>()
                                    .Where(cc => cc.Name == createCharacter.CharacterName).List().FirstOrDefault();
                            if (character != null)
                            {
                                Log.DebugFormat("null character");
                                transaction.Commit();
                                serverPeer.SendOperationResponse(
                                    new OperationResponse(message.Code)
                                    {
                                        ReturnCode = (int) ErrorCode.InvalidCharacter,
                                        DebugMessage = "Character name taken",
                                        Parameters = para
                                    }, new SendParameters());
                            }
                            else
                            {
                                Log.DebugFormat("creating character");
                                var newChar = new ComplexCharacter
                                {
                                    UserId = user,
                                    Name = createCharacter.CharacterName,
                                    Class = createCharacter.CharacterClass,
                                    Sex = createCharacter.Sex,
                                    Level = 1
                                };

                                session.Save(newChar);
                                transaction.Commit();
                                serverPeer.SendOperationResponse(
                                    new OperationResponse(message.Code)
                                    {
                                        ReturnCode = (int) ErrorCode.Ok,
                                        Parameters = para
                                    }, new SendParameters());
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                Log.DebugFormat("invalid character");
                Log.Error(e);
                serverPeer.SendOperationResponse(
                    new OperationResponse(message.Code)
                    {
                        ReturnCode = (int) ErrorCode.InvalidCharacter,
                        DebugMessage = e.ToString(),
                        Parameters = para
                    }, new SendParameters());
            }
            return true;
        }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var para = new Dictionary<byte, object>
            {
                {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]},
                {
                    (byte) ClientParameterCode.SubOperationCode,
                    message.Parameters[(byte) ClientParameterCode.SubOperationCode]
                }
            };

            var operation = new SelectCharacter(serverPeer.Protocol, message);
            if (!operation.IsValid)
            {
                Log.Error(operation.GetErrorMessage());
                serverPeer.SendOperationResponse(
                    new OperationResponse(message.Code)
                    {
                        ReturnCode = (int) ErrorCode.OperationInvalid,
                        DebugMessage = operation.GetErrorMessage(),
                        Parameters = para
                    }, new SendParameters());
                return true;
            }
            try
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        var user =
                            session.QueryOver<User>().Where(ua => ua.Id == operation.UserId).List().FirstOrDefault();
                        if (user != null)
                        {
                            Log.DebugFormat("Found user {0}", user.Username);

                        }
                        var character =
                            session.QueryOver<ComplexCharacter>()
                                .Where(cc => cc.UserId == user)
                                .And(cc => cc.Id == operation.CharacterId)
                                .List()
                                .FirstOrDefault();
                        transaction.Commit();

                        if (character == null)
                        {
                            serverPeer.SendOperationResponse(
                                new OperationResponse(message.Code)
                                {
                                    ReturnCode = (int) ErrorCode.InvalidCharacter,
                                    DebugMessage = "Invalid Character",
                                    Parameters = para
                                }, new SendParameters());
                        }
                        else
                        {
                            Log.DebugFormat("Found character {0}", character.Name);
                            para.Add((byte) ClientParameterCode.CharacterId, character.Id);
                            serverPeer.SendOperationResponse(
                                new OperationResponse(message.Code)
                                {
                                    ReturnCode = (byte) ErrorCode.Ok,
                                    Parameters = para
                                },
                                new SendParameters());
                        }
                    }
                }
                return true;
            }
            catch (Exception e)
            {
                Log.Error(e);
                serverPeer.SendOperationResponse(
                    new OperationResponse(message.Code)
                    {
                        ReturnCode = (int) ErrorCode.InvalidCharacter,
                        DebugMessage = e.ToString(),
                        Parameters = para
                    }, new SendParameters());
            }
            return true;
        }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            var operation = new RegisterSecurely(serverPeer.Protocol, message);
            if (!operation.IsValid)
            {
                serverPeer.SendOperationResponse(new OperationResponse(message.Code,
                    new Dictionary<byte, object>
                    {
                        {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]}
                    })
                {
                    ReturnCode = (int) ErrorCode.OperationInvalid,
                    DebugMessage = operation.GetErrorMessage()
                }, new SendParameters());
                return true;
            }

            if (operation.UserName == "" | operation.Email == "" | operation.Password == "")
            {
                serverPeer.SendOperationResponse(new OperationResponse(message.Code,
                   new Dictionary<byte, object>
                   {
                        {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]}
                   })
                {
                    ReturnCode = (int)ErrorCode.OperationInvalid,
                    DebugMessage = "All Fields are Required"
                }, new SendParameters());
                return true;
            }
            try
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        Log.DebugFormat("about to look for user account {0}", operation.UserName);
                        var userList = session.QueryOver<User>().Where(u => u.Username == operation.UserName).List();
                        if (userList.Count > 0)
                        {
                            Log.DebugFormat("Found account name already in use.");
                            transaction.Commit();
                            serverPeer.SendOperationResponse(
                                new OperationResponse(message.Code)
                                {
                                    ReturnCode = (int) ErrorCode.UserNameInUse,
                                    DebugMessage = "Account name already in use please use another."
                                }, new SendParameters());
                            return true;
                        }

                        var salt = Guid.NewGuid().ToString().Replace("-", "");
                        Log.DebugFormat("Created salt {0}", salt);
                        var newUser = new User
                        {
                            Email = operation.Email,
                            Username = operation.UserName,
                            //TODO may need to change back to SHA1
                            Password =
                                BitConverter.ToString(SHA1.Create().ComputeHash(
                                    Encoding.UTF8.GetBytes(salt + operation.Password))).Replace("-", ""),
                            Salt = salt,
                            Algorithm = "sha1",
                            Created = DateTime.Now,
                            Updated = DateTime.Now
                        };

                        Log.DebugFormat("built user opbject");
                        session.Save(newUser);
                        Log.DebugFormat("Saved new user");
                        transaction.Commit();
                    }
                    using (var transaction = session.BeginTransaction())
                    {
                        Log.DebugFormat("looking up newly creaded user");
                        var userList = session.QueryOver<User>().Where(u => u.Username == operation.UserName).List();
                        if (userList.Count > 0)
                        {
                            Log.DebugFormat("creating profile");
                            UserProfile profile = new UserProfile() { CharacterSlots = 1, UserId = userList[0]};
                            session.Save(profile);
                            Log.DebugFormat("saved profile");
                            transaction.Commit();
                        }
                    }

                    serverPeer.SendOperationResponse(
                        new OperationResponse(message.Code) {ReturnCode = (byte) ClientReturnCode.UserCreated},
                        new SendParameters());
                }
            }
            catch (Exception e)
            {
                Log.Error("Error Occured", e);
                serverPeer.SendOperationResponse(new OperationResponse(message.Code,
                    new Dictionary<byte, object>
                    {
                        {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]}
                    })
                {
                    ReturnCode = (int) ErrorCode.UserNameInUse,
                    //remove debug msg later
                    DebugMessage = e.ToString()
                }, new SendParameters());
            }
            return true;
        }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.DebugFormat("Login message being handled message code {0}", message.Code);
            var operation = new LoginSecurely(serverPeer.Protocol, message);
            if (!operation.IsValid)
            {
                serverPeer.SendOperationResponse(new OperationResponse(message.Code,
                    new Dictionary<byte, object>
                    {
                        {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]}
                    })
                {
                    ReturnCode = (int) ErrorCode.OperationInvalid,
                    DebugMessage = operation.GetErrorMessage()
                }, new SendParameters());
                return true;
            }

            if (operation.UserName == "" | operation.Password == "")
            {
                serverPeer.SendOperationResponse(new OperationResponse(message.Code,
                    new Dictionary<byte, object>
                    {
                        {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]}
                    })
                {
                    ReturnCode = (int) ErrorCode.IncorrectUserNameOrPassword,
                    DebugMessage = "User name or password is incorrect"
                }, new SendParameters());
                return true;
            }
            try
            {
                using (var session = NHibernateHelper.OpenSession())
                {
                    using (var transaction = session.BeginTransaction())
                    {
                        Log.DebugFormat("about to look for user account {0}", operation.UserName);
                        var userList = session.QueryOver<User>().Where(u => u.Username == operation.UserName).List();
                        if (userList.Count > 0)
                        {
                            Log.DebugFormat("found user {0} in database", operation.UserName);
                            var user = userList[0];
                            var hash = BitConverter.ToString(SHA1.Create().ComputeHash(
                                Encoding.UTF8.GetBytes(user.Salt + operation.Password)))
                                .Replace("-", "");
                            Log.DebugFormat("original pass {0}", hash.Trim());
                            Log.DebugFormat("login pass {0}", user.Password.Trim());

                            if (String.Equals(hash.Trim(), user.Password.Trim(), StringComparison.OrdinalIgnoreCase))
                            {
                                LoginServer server = Server as LoginServer;
                                if (server != null)
                                {
                                    bool founduser = false;
                                    foreach (var subServerClientPeer in server.ConnectionCollection<SubServerConnectionCollection>().Clients)
                                    {
                                        if (subServerClientPeer.Value.ClientData<CharacterData>().UserId == user.Id)
                                        {
                                            founduser = true;
                                        }
                                    }
                                    if (founduser)
                                    {
                                        Log.DebugFormat("user is already logged in");
                                        var para = new Dictionary<byte, object>
                                        {
                                            {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]},
                                            {(byte) ClientParameterCode.SubOperationCode, message.Parameters[(byte) ClientParameterCode.SubOperationCode]}
                                        };
                                        serverPeer.SendOperationResponse(
                                            new OperationResponse((byte) ClientOperationCode.Login)
                                            {
                                                Parameters = para,
                                                ReturnCode = (short) ErrorCode.UserCurrentlyLoggedIn,
                                                DebugMessage = "User is currently logged in."
                                            }, new SendParameters());
                                    }
                                    else
                                    {
                                        Log.Debug("Login handler successfully found character to log in.");

                                        server.ConnectionCollection<SubServerConnectionCollection>().Clients.Add(new Guid((Byte[]) message.Parameters[(byte) ClientParameterCode.PeerId]), _clientFactory());
                                        server.ConnectionCollection<SubServerConnectionCollection>().Clients[new Guid((Byte[])message.Parameters[(byte)ClientParameterCode.PeerId])].ClientData<CharacterData>().UserId = user.Id;
                                        var para = new Dictionary<byte, object>
                                        {
                                            {
                                                (byte) ClientParameterCode.PeerId,
                                                message.Parameters[(byte) ClientParameterCode.PeerId]
                                            },
                                            {
                                                (byte) ClientParameterCode.SubOperationCode,
                                                message.Parameters[(byte) ClientParameterCode.SubOperationCode]
                                            },
                                            {(byte) ClientParameterCode.UserId, user.Id}
                                        };
                                        serverPeer.SendOperationResponse(
                                            new OperationResponse((byte) ClientOperationCode.Login) {Parameters = para},
                                            new SendParameters());
                                    }
                                }
                                return true;
                            }
                            Log.Debug("password does not match.");

                            serverPeer.SendOperationResponse(new OperationResponse(message.Code,
                                new Dictionary<byte, object>
                                {
                                    {
                                        (byte) ClientParameterCode.PeerId,
                                        message.Parameters[(byte) ClientParameterCode.PeerId]
                                    }
                                })
                            {
                                ReturnCode = (int) ErrorCode.IncorrectUserNameOrPassword,
                                DebugMessage = "User name or password is incorrect"
                            }, new SendParameters());
                            return true;
                        }
                        Log.DebugFormat("Account name does not exist {0}", operation.UserName);
                        transaction.Commit();
                        serverPeer.SendOperationResponse(
                            new OperationResponse(message.Code)
                            {
                                ReturnCode = (int) ErrorCode.IncorrectUserNameOrPassword,
                                DebugMessage = "User name or password is incorrect."
                            }, new SendParameters());
                        return true;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Error Occured", e);
                serverPeer.SendOperationResponse(new OperationResponse(message.Code,
                    new Dictionary<byte, object>
                    {
                        {(byte) ClientParameterCode.PeerId, message.Parameters[(byte) ClientParameterCode.PeerId]}
                    })
                {
                    ReturnCode = (int) ErrorCode.IncorrectUserNameOrPassword,
                    //remove debug msg later
                    DebugMessage = e.ToString()
                }, new SendParameters());
            }
            return true;
        }
 public override void Disconnect(PhotonServerPeer serverPeer)
 {
     if (serverPeer.ServerId.HasValue)
     {
         if (ChatServer != null && serverPeer.ServerId.Value == ChatServer.ServerId)
         {
             ChatServer = null;
         }
         if (LoginServer != null && serverPeer.ServerId.Value == LoginServer.ServerId)
         {
             LoginServer = null;
         }
     }
 }
        public override void ResetServers()
        {
            Log.DebugFormat("Reseting servers");
            if (ChatServer != null && ChatServer.ServerType != (int) ServerType.Chat)
            {
                var peer =
                    Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int) ServerType.Chat)
                        .FirstOrDefault();
                if (peer != null)
                {
                    ChatServer = peer;
                }
            }

            if (LoginServer != null && LoginServer.ServerType != (int) ServerType.Login)
            {
                Log.DebugFormat("Reseting login");

                var peer =
                    Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int) ServerType.Login)
                        .FirstOrDefault();
                if (peer != null)
                {
                    LoginServer = peer;
                }
            }

            if (ChatServer == null || ChatServer.ServerId == null)
            {
                ChatServer =
                    Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int) ServerType.Chat)
                        .FirstOrDefault() ??
                    Servers.Values.Where(subServerPeer => (subServerPeer.ServerType & (int) ServerType.Chat) != 0)
                        .FirstOrDefault();
            }

            if (LoginServer == null || LoginServer.ServerId == null)
            {
                Log.DebugFormat("Reseting login");

                LoginServer =
                    Servers.Values.Where(subServerPeer => subServerPeer.ServerType == (int) ServerType.Login)
                        .FirstOrDefault() ??
                    Servers.Values.Where(subServerPeer => (subServerPeer.ServerType & (int) ServerType.Login) != 0)
                        .FirstOrDefault();
            }

            if (LoginServer != null)
            {
                Log.DebugFormat("LoginSErver : {0}", LoginServer.ConnectionId);
            }
            if (ChatServer != null)
            {
                Log.DebugFormat("ChatServer  : {0}", ChatServer.ConnectionId);
            }
        }
 public override void Connect(PhotonServerPeer serverPeer)
 {
     if ((serverPeer.ServerType & (int) ServerType.Region) != 0)
     {
         var parameters = new Dictionary<byte, object>();
         var serverList = Servers.Where(
             incomingSubServerPeer =>
                 incomingSubServerPeer.Value.ServerId.HasValue &&
                 !incomingSubServerPeer.Value.ServerId.Equals(serverPeer.ServerId) &&
                 (incomingSubServerPeer.Value.ServerType & (int) ServerType.Region) != 0)
             .ToDictionary(incomingSubServerPeer => incomingSubServerPeer.Value.ApplicationName,
                 incomingSubServerPeer => incomingSubServerPeer.Value.TcpAddress);
         if (serverList.Count > 0)
         {
             if (Log.IsDebugEnabled)
             {
                 Log.DebugFormat("Sending list of {0} connected sub servers ", serverList.Count);
             }
             parameters.Add((byte) ServerParameterCode.SubServerDictionary, serverList);
             serverPeer.SendEvent(new EventData((byte) ServerEventCode.SubServerList, parameters),
                 new SendParameters());
         }
     }
 }
        protected override bool OnHandleMessage(IMessage message, PhotonServerPeer serverPeer)
        {
            Log.ErrorFormat("No existing event Handler. code: {0} type {1} subcode {2}", message.Code, message.GetType(), message.SubCode);

            return true;
        }