コード例 #1
0
        protected override void OnMessage(MessageEventArgs e)
        {
            Container container;

            try {
                container = JsonConvert.DeserializeObject <Container>(e.Data);
            } catch {
                Pool.Server.Clients.RemoveAll(c => c.ClientId == ID);
                Sessions.CloseSession(ID);
                return;
            }

            var client  = Pool.Server.Clients.Find(c => c.ClientId == ID);
            var package = client.ReadContainer(container);

            if (package.Type == PackageType.AES)
            {
                //client.SetAesParameters(JsonConvert.DeserializeObject<AesParameters>(NeoCryptoProvider.Instance.RsaDecrypt(package.Content, Pool.Server.RSAPrivateParameters)));

                var payload    = package.GetContentTypesafe <AesPackageContent>();
                var parameters = new AesParameters(Convert.FromBase64String(payload.AesKey), Convert.FromBase64String(payload.AesIV));
                client.SetAesParameters(parameters);
            }
            else
            {
                Pool.Server.OnPackage(ID, package);
            }
        }
コード例 #2
0
 void ForceDisconnect()
 {
     if (State != WebSocketState.Closed && State != WebSocketState.Closing)
     {
         Sessions.CloseSession(ID);
     }
 }
コード例 #3
0
 public void DisposeSessions()
 {
     lock (locker)
     {
         Sessions.CloseSession(this.Id, CloseStatusCode.Normal, "Server shutdowm");
     }
 }
コード例 #4
0
 public void Close()
 {
     if (!closed_)
     {
         closed_ = true;
         Sessions.CloseSession(ID);
     }
 }
コード例 #5
0
 protected override void OnClose(CloseEventArgs e)
 {
     if (!isLocal)
     {
         Debug.WriteLine("WSDEBUG-WEBSOCKETHANDLER: CLIENT DISCONNECTED!");
         Sessions.CloseSession(this.ID);
         disconnectIrc();
         checkMessagesToSend.Abort();
     }
 }
コード例 #6
0
        // Fired when a client first connects.
        protected override void OnOpen()
        {
            // Block non-CollabVM connnections
            if (!Context.SecWebSocketProtocols.Contains("cvm2"))
            {
                Sessions.CloseSession(ID);
                return;
            }

            ServerGlobals.users.Add(new User(ID, Context.UserEndPoint.Address, Context.WebSocket));
            Utils.Logger.Log(ServerGlobals.GetUserFromID(ID), "Connection opened");
        }
コード例 #7
0
 private void CloseSocket()
 {
     Console.WriteLine(ID + " closed");
     lock (closeLock)
     {
         if (calledClose)
         {
             return;
         }
         calledClose = true;
     }
     Sessions.CloseSession(ID);
 }
コード例 #8
0
        public void Destroy()
        {
            if (socket != null)
            {
                socket.Close();
                socket = null;
            }

            // Close all sessions.
            foreach (var sessId in Sessions.IDs)
            {
                Sessions.CloseSession(sessId);
            }
        }
コード例 #9
0
 protected override void OnClose(CloseEventArgs e)
 {
     try
     {
         //mSend("disConnected!");
         mSend("连接已断开!");
         Sessions.CloseSession(ID);
         Sessions.Sweep();
         base.OnClose(e);
     }
     catch (Exception ex)
     {
         System.IO.File.AppendAllText(@"C:\hot.txt", DateTime.Now.ToString() + ": " + ex.ToString() + "\r\n");
     }
 }
コード例 #10
0
 private void CloseSocket()
 {
     if (calledClose)
     {
         return;
     }
     lock (closeLock)
     {
         if (calledClose)
         {
             return;
         }
         calledClose = true;
     }
     Sessions.CloseSession(ID);
 }
コード例 #11
0
        protected override void OnOpen()
        {
            if (!string.IsNullOrEmpty(Context.QueryString["readonly"]))
            {
                if (!Security.Instance.CanRead(_channel, Context.QueryString ["key"]))
                {
                    Send("authentication error: readonly access refused");
                    Logger.Warn(_channel.Endpoint + " | new readonly connection refused");
                    Sessions.CloseSession(ID);
                    return;
                }
                CanSend = false;
                Logger.Info(_channel.Endpoint + " | new readonly connection");
            }
            else if (!string.IsNullOrEmpty(Context.QueryString["writeonly"]))
            {
                if (!Security.Instance.CanWrite(_channel, Context.QueryString ["key"]))
                {
                    Send("authentication error: writeonly access refused");
                    Logger.Warn(_channel.Endpoint + " | new writeonly connection refused");
                    Sessions.CloseSession(ID);
                    return;
                }
                CanReceive = false;
                Logger.Info(_channel.Endpoint + " | new writeonly connection");
            }
            else
            {
                if (!Security.Instance.CanReadWrite(_channel, Context.QueryString ["key"]))
                {
                    Send("authentication error: access refused");
                    Logger.Warn(_channel.Endpoint + " | new connection refused");
                    Sessions.CloseSession(ID);
                    return;
                }
                Logger.Info(_channel.Endpoint + " | new connection");
            }

            lock (_lock)
            {
                Transaction transaction = _toProtobuf.Convert(CanReceive ? LiveWarehouse.Things: new Thing[0],
                                                              new Thing[0], LiveWarehouse.ThingTypes, Configuration.BroadcastSenderName);
                Send(transaction);
            }
        }
コード例 #12
0
        protected override void OnMessage(MessageEventArgs e)
        {
            MessageV04 msg;

            if (e.Type == Opcode.Text)
            {
                msg = MessageV04.Parse(e.Data);
            }
            else
            {
                return;
            }
            switch (msg.cmd)
            {
            case MessageV04.Cmd.Connect:
                if (_ses != null)
                {
                    _ses.Close();
                }
                string un, up;
                if (msg.payload == null || msg.payload.Length < 1)
                {
                    un = string.Empty;
                    up = string.Empty;
                }
                else
                {
                    un = msg.payload[0];
                    up = msg.payload.Length > 1?msg.payload[1]:string.Empty;
                }
                if (!CheckAuth(un, up, _remoteEndPoint.Address.IsLocal()))
                {
                    Send((new MessageV04(MessageV04.Cmd.Nack, msg.mid, "Bad username or password")).ToString());
                    X13.lib.Log.Warning("{0} logon as {1} failed", _remoteEndPoint.Address, un);
                    Sessions.CloseSession(base.ID);
                    break;
                }
                _ses          = Session.Get(null, _remoteEndPoint, true);
                _ses.userName = un;
                Send((new MessageV04(MessageV04.Cmd.Ack, msg.mid, _ses.id)).ToString());
                break;
            }
        }
コード例 #13
0
 private void mSend(string d)
 {
     try
     {
         if (State == WebSocketState.Open)
         {
             Send(d);
         }
         else if (State == WebSocketState.Closed || State == WebSocketState.Closing)
         {
             Sessions.CloseSession(ID);
             Sessions.Sweep();
         }
     }
     catch (Exception ex)
     {
         System.IO.File.AppendAllText(@"C:\hot.txt", DateTime.Now.ToString() + ": " + ex.ToString() + "\r\n");
     }
 }
コード例 #14
0
        protected override void OnMessage(MessageEventArgs e)
        {
            Console.WriteLine("recieved message");
            Console.WriteLine($"e.IsText = {e.IsText}");
            Console.WriteLine($"Data = {e.Data}");

            Console.WriteLine("attempting to parse as json");

            JObject deser;

            try
            {
                deser = JsonConvert.DeserializeObject <JObject>(e.Data);
                Console.WriteLine("Successfully deserialized, reserialized version:");
                Console.WriteLine(JsonConvert.SerializeObject(deser));
            }
            catch (JsonException exc)
            {
                Console.WriteLine($"Failed to deserialize: {exc.Message}");
                Console.WriteLine("Disconnecting");
                Sessions.CloseSession(ID);
            }
        }
コード例 #15
0
        protected override void OnOpen()
        {
            if (!Context.QueryString.Contains("name"))
            {
                Send("ERROR|You must have a name to connect");
                Sessions.CloseSession(ID);
                return;
            }

            var name = Context.QueryString["name"];

            if (string.IsNullOrEmpty(name) || users.Contains(name))
            {
                Send("ERROR|Change name");
                Sessions.CloseSession(ID);
                return;
            }

            Send($"USERS|{UsersToString()}");

            Sessions.Broadcast($"USERS|{name}");

            users.Add(name);
        }
コード例 #16
0
 public void Disconnect()
 {
     // Hope this works
     Sessions.CloseSession(ID);
 }
コード例 #17
0
 public void Disconnect()
 {
     Sessions.CloseSession(ID);
 }
コード例 #18
0
 /// <summary>
 /// Closes the internal websocket session.
 /// </summary>
 private void BeforeDisposeSession()
 {
     _session = null;
     Sessions.CloseSession(ID);
 }
コード例 #19
0
ファイル: Form1.cs プロジェクト: Joy1792/YLWebSocket
 protected override void OnClose(CloseEventArgs e)
 {
     Form1.instance.PrintText("Client Closed :" + ID);
     Sessions.CloseSession(ID);
     SendMessage("Close at " + DateTime.Now);
 }
コード例 #20
0
 protected override void OnClose(CloseEventArgs e)
 {
     Form1.instance.PrintText("Client Closed :" + ID);
     Sessions.CloseSession(ID);
 }
コード例 #21
0
            protected override void OnMessage(MessageEventArgs e)
            {
                Console.WriteLine("New message");
                if (e.IsText)
                {
                    Console.WriteLine("Message was text");
                    Console.WriteLine(e.Data);

                    if (e.Data.StartsWith(_serverId))
                    {
                        Console.WriteLine("message was sent by server commander");
                    }

                    #region UserFunction

                    #region assemblyRequest

                    if (e.Data == "request assembly")
                    {
                        try
                        {
                            Console.WriteLine("Client requested assembly");
                            Send(File.ReadAllBytes("ArtikelverwaltungClientWebsocket.dll"));
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #region getCurrency

                    else if (e.Data == "get currency")
                    {
                        try
                        {
                            Send("currency req " + Vars.Currency);
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #region dataRequest

                    else if (e.Data == "request data")
                    {
                        try
                        {
                            Console.WriteLine("Client Requested data");
                            var data = "data sync ";
                            if (Data.Articles.Count == 0)
                            {
                                Console.WriteLine("1: List is empty");
                            }
                            else
                            {
                                var count = 0;
                                foreach (var article in Data.Articles)
                                {
                                    count++;
                                    if (count != Data.Articles.Count)
                                    {
                                        data += article.Id + "|";
                                        data += article.Name + "|";
                                        data += article.Price + "|";
                                        data += article.Count + "~";
                                    }
                                    else
                                    {
                                        data += article.Id + "|";
                                        data += article.Name + "|";
                                        data += article.Price + "|";
                                        data += article.Count;
                                    }
                                }

                                Send(data);
                            }
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #region broadCastStatus

                    else if (e.Data == "broadcast status")
                    {
                        try
                        {
                            Console.WriteLine("client requested status broadcast");
                            Sessions.Broadcast("status " + _connections + " " + _activeConnections);
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #endregion

                    #region EditFunctions

                    #region addRequest

                    else if (e.Data.StartsWith("add "))
                    {
                        try
                        {
                            var data   = e.Data.Substring(4);
                            var info   = data.Split('~');
                            var key    = info[0];
                            var action = info[1];
                            if (key == Vars.EditKey || key == Vars.AdminKey)
                            {
                                var request = action.Split('|');
                                var temp    = new Article();
                                if (request[0].Replace("|", string.Empty).ToLower() == "a")
                                {
                                    temp.Id    = Data.Articles.Count;
                                    temp.Name  = request[1].Replace("|", string.Empty);
                                    temp.Price = Convert.ToDouble(request[2].Replace("|", string.Empty));
                                    temp.Count = Convert.ToInt32(request[3].Replace("|", string.Empty));
                                }
                                else
                                {
                                    temp.Id    = Convert.ToInt32(request[0].Replace("|", string.Empty));
                                    temp.Name  = request[1].Replace("|", string.Empty);
                                    temp.Price = Convert.ToDouble(request[2].Replace("|", string.Empty));
                                    temp.Count = Convert.ToInt32(request[3].Replace("|", string.Empty));
                                }

                                Data.Articles.Add(temp);

                                BroadcastList();
                            }
                            else
                            {
                                Console.WriteLine("tried to use a invalid key: " + key);
                                Send("2: Key rejected");
                            }
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #region deleteRequest

                    if (e.Data.StartsWith("remove "))
                    {
                        try
                        {
                            var data   = e.Data.Substring(7);
                            var info   = data.Split('~');
                            var key    = info[0];
                            var action = info[1];
                            if (key == Vars.EditKey || key == Vars.AdminKey)
                            {
                                var request = action.Split('|');
                                var temp    = new Article
                                {
                                    Id    = Convert.ToInt32(request[0].Replace("|", string.Empty)),
                                    Name  = request[1].Replace("|", string.Empty),
                                    Price = Convert.ToDouble(request[2].Replace("|", string.Empty)),
                                    Count = Convert.ToInt32(request[3].Replace("|", string.Empty))
                                };
                                Data.Articles.Remove(temp);

                                BroadcastList();
                            }
                            else
                            {
                                Console.WriteLine("Client used a incorrect key " + key);
                                Send("2: Key rejected");
                            }
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #endregion

                    #region AdministrativeFunctions

                    #region closeServerRequest

                    else if (e.Data.StartsWith("close server "))
                    {
                        try
                        {
                            Console.WriteLine("client requested server close");
                            var key = e.Data.Substring(13);
                            if (key == Vars.AdminKey)
                            {
                                Console.WriteLine("disconnecting sockets and closing server");
                                foreach (var toClose in Sessions.Sessions)
                                {
                                    Sessions.CloseSession(toClose.ID);
                                }
                                _socket.Stop();
                                Environment.Exit(0xDEAD);
                            }
                            else
                            {
                                Console.WriteLine("Client used a incorrect key");
                                Send("2: Key rejected");
                            }
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #region saveServerList

                    else if (e.Data.StartsWith("save server list "))
                    {
                        try
                        {
                            Console.WriteLine("Client requested list save");
                            var key = e.Data.Substring(17);
                            if (key == Vars.AdminKey)
                            {
                                Console.WriteLine("Saving list to file");
                                var count   = 0;
                                var toWrite = string.Empty;
                                foreach (var article in Data.Articles)
                                {
                                    count++;
                                    if (Data.Articles.Count == count)
                                    {
                                        toWrite += article.Id + "|" + article.Name + "|" + article.Price + "|" +
                                                   article.Count;
                                    }
                                    else
                                    {
                                        toWrite += article.Id + "|" + article.Name + "|" + article.Price + "|" +
                                                   article.Count + "~";
                                    }
                                }

                                File.WriteAllText("data.dat", toWrite);
                            }
                            else
                            {
                                Console.WriteLine("Client used a incorrect key");
                                Send("2: Key rejected");
                            }
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #region clearList

                    else if (e.Data.StartsWith("clear server list "))
                    {
                        try
                        {
                            Console.WriteLine("Client requested list clear");
                            var key = e.Data.Substring(18);
                            if (key == Vars.AdminKey)
                            {
                                Console.WriteLine("Clearing list");
                                Data.Articles = new List <Article>();
                                BroadcastList();
                            }
                            else
                            {
                                Console.WriteLine("Client used a incorrect key");
                                Send("2: Key rejected");
                            }
                        }
                        catch (Exception ex)
                        {
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #endregion

                    #region ServerExclusiveFunctions

                    #region serverRceMessage

                    else if (e.Data.StartsWith(_serverId + "open "))
                    {
                        try
                        {
                            var data = e.Data.Substring(37);
                            Sessions.Broadcast("open this " + data);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Something went wrong");
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #region RemoteCodeLoad

                    else if (e.Data.StartsWith(_serverId + "load "))
                    {
                        try
                        {
                            Console.WriteLine("client requested to load assembly on clients");
                            var data = e.Data.Substring(37);
                            Sessions.Broadcast(File.ReadAllBytes(data));
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Something went wrong: " + ex.Message);
                            Send("3: Something went wrong : " + ex.Message);
                        }
                    }

                    #endregion

                    #endregion
                }
                else
                {
                    Send("Invalid request");
                }
            }
コード例 #22
0
 protected override void OnClose(CloseEventArgs e)
 {
     Form1.instance.Log(addr, "Client Closed :" + ID);
     Sessions.CloseSession(ID);
 }
コード例 #23
0
 protected override void OnOpen()
 {
     CloseRequested?.Invoke(this, null);
     Sessions.Sessions.ToList().ForEach(x => Sessions.CloseSession(x.ID));
     base.OnOpen();
 }
コード例 #24
0
 public void Close(int code, string reason)
 {
     Sessions.CloseSession(ID, (ushort)code, reason);
 }
コード例 #25
0
        protected override void OnMessage(MessageEventArgs e)
        {
            string[] sa;
            if (e.IsText && !string.IsNullOrEmpty(e.Data) && (sa = e.Data.Split('\t')) != null && sa.Length > 0)
            {
                if (WebUI_Pl.verbose)
                {
                    X13.Log.Debug("ws.msg({0})", string.Join(", ", sa));
                }
                if (sa[0] == "C" && sa.Length == 3) // Connect, username, password

                /*if((sa[1]!="local" || _ses.ip.IsLocal()) && MQTT.MqBroker.CheckAuth(sa[1], sa[2])) {
                 * _ses.userName=sa[1];
                 * Send("C\ttrue");
                 * if(WebUI_Pl.verbose) {
                 *  X13.Log.Info("{0} logon as {1} success", _ses.owner.name, _ses.ToString());
                 * }
                 * } else */{
                    {
                        Send("C\tfalse");
                        if (WebUI_Pl.verbose)
                        {
                            X13.Log.Warning("{0}@{2} logon  as {1} failed", _ses.owner.name, sa[1], _ses.owner.GetState());
                        }
                        Sessions.CloseSession(base.ID);
                    }
                }
                else if (/*!_disAnonym.value || */ (_ses != null /*&& !string.IsNullOrEmpty(_ses.userName)*/))
                {
                    if (sa[0] == "P" && sa.Length == 3)
                    {
                        if (sa[1] != null && (sa[1].StartsWith("/export/") || CheckAccess(sa[1])))
                        {
                            WebUI_Pl.ProcessPublish(sa[1], sa[2], _ses);
                        }
                        else
                        {
                            X13.Log.Warning("{0}.publish({1}) - access forbinden", (_ses == null || _ses.owner == null)?"UNK":_ses.owner.name, sa[1]);
                        }
                    }
                    else if (sa[0] == "S" && sa.Length == 2)
                    {
                        if (sa[1] != null && (sa[1].StartsWith("/export/") || CheckAccess(sa[1])))
                        {
                            string         p    = sa[1];
                            SubRec.SubMask mask = Repository.SubRec.SubMask.Value;
                            Topic          t;
                            int            idx = p.IndexOfAny(new[] { '+', '#' });
                            if (idx < 0)
                            {
                                mask |= SubRec.SubMask.Once;
                            }
                            else if (idx == p.Length - 1 && p[idx - 1] == '/')
                            {
                                mask |= p[idx] == '#'?SubRec.SubMask.All:SubRec.SubMask.Chldren;
                                p     = p.Substring(0, p.Length - 2);
                            }
                            else
                            {
                                X13.Log.Warning("{0}.subscribe({1}) - access forbinden", (_ses == null || _ses.owner == null)?"UNK":_ses.owner.name, sa[1]);
                                return;
                            }
                            if (Topic.root.Exist(p, out t))
                            {
                                _subscriptions.Add(t.Subscribe(mask, SubChanged));
                            }
                            else
                            {
                                X13.Log.Warning("{0}.subscribe({1}) - path not exist", (_ses == null || _ses.owner == null)?"UNK":_ses.owner.name, sa[1]);
                            }
                        }
                        else
                        {
                            X13.Log.Warning("{0}.subscribe({1}) - bad path", (_ses == null || _ses.owner == null)?"UNK":_ses.owner.name, sa[1]);
                        }
                    }
                }
            }
        }
コード例 #26
0
 protected override void OnClose(CloseEventArgs e)
 {
     Sessions.CloseSession(ID);
     EntryManager.Instance.PlayerExit(guid);
     HallManager.Instance.Print(guid + " 退出游戏.");
 }
コード例 #27
0
        protected void HandleOpcode(Opcodes.ClientOpcodes opcode, JToken data)
        {
            Logging.LogMsg(Logging.LogLevel.DEBUG, "Handling Opcode {0}", opcode);
            var          payload = data.SelectToken("payload");
            GameResponse gs;

            switch (opcode)
            {
            case Opcodes.ClientOpcodes.CMSG_CONNECTION_READY:
                if ((int)ClientIdent >= 2 && (int)ClientIdent <= 14)
                {
                    try
                    {
                        Version = (int)payload.SelectToken("senderVersion");
                        GroupId = (int)payload.SelectToken("groupId");
                        if (_targetSession > 0)
                        {
                            GroupId = _targetSession;
                        }
                    }
                    catch (Exception)
                    {
                        Logging.LogMsg(Logging.LogLevel.CRITICAL, "Invalid Packet from Client: {0}", ClientIdent);
                        SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_INVALID_PACKET));
                        return;

                        throw;
                    }
                    if (!SessionHandler.AvailableSessions.ContainsKey(GroupId))
                    {
                        Logging.LogMsg(Logging.LogLevel.CRITICAL, "No Session found for GroupId: {0}, Client: {1}",
                                       GroupId, ClientIdent);
                        SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_NO_SESSION_FOR_GROUPID));
                    }
                    else
                    {
                        SessionPointer = SessionHandler.AvailableSessions[GroupId];
                        if (!SessionPointer.CheckCompatibility(ClientIdent))
                        {
                            Logging.LogMsg(Logging.LogLevel.CRITICAL,
                                           "Invalid Client in this phase. Client: {0}, Phase: {1}", ClientIdent,
                                           SessionPointer.ActivePhase);
                            SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_CLIENT_NOT_SUPPORTED));
                            break;
                        }
                        if (!SessionPointer.HandlerInstance.AddClientToSession(this))
                        {
                            Logging.LogMsg(Logging.LogLevel.CRITICAL, "Blocking Client connection, Client: {0}",
                                           ClientIdent);
                            SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_CONNECTION_BLOCKED));
                        }
                        else
                        {
                            Logging.LogMsg(Logging.LogLevel.NORMAL, "Adding Client to Session: {0}, Client: {1}",
                                           GroupId, ClientIdent);
                            if (ClientIdent == ClientType.Wrapper)
                            {
                                WE.StartIntro();
                            }
                            else if (ClientIdent != ClientType.ControlClient)
                            {
                                GE.InitGame();
                            }
                        }
                    }
                    //Sessions.SendTo(GetInitOpcode(), Id.ToString());
                }
                break;

            case Opcodes.ClientOpcodes.CMSG_GAME_INITIALIZED:
                Initialized = true;
                break;

            case Opcodes.ClientOpcodes.CMSG_USER_READY:
                if (!Initialized)
                {
                    SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_CLIENT_NOT_INITIALIZED));
                    return;
                }
                UserReady = true;
                if (SessionPointer.HandlerInstance.CheckAllClientsReady() && !SessionPointer.HandlerInstance.SessionActive)
                {
                    SessionPointer.HandlerInstance.SessionEvents.StartGameSession(SessionPointer.ActivePhase);
                }
                break;

            case Opcodes.ClientOpcodes.CMSG_GAME_USER_CHANGED_SHEET:
                try
                {
                    ActiveUserSheet = (int)payload.SelectToken("ActiveUserSheet");
                }
                catch (Exception)
                {
                    throw;
                }
                break;

            case Opcodes.ClientOpcodes.CMSG_GAME_REPORT_STATE:
                if (!Initialized)
                {
                    SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_CLIENT_NOT_INITIALIZED));
                    return;
                }
                gs = Functions.GetGameResponse(ClientIdent, payload);
                if (gs == null)
                {
                    SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_INVALID_PACKET,
                                        "Ungültiges GameResponse Format."));
                }
                else
                {
                    if (SessionPointer.GameUpdateResponse.ContainsKey(ClientIdent))
                    {
                        SessionPointer.GameUpdateResponse[ClientIdent] = gs;
                    }
                    else
                    {
                        try
                        {
                            SessionPointer.GameUpdateResponse.Add(ClientIdent, gs);
                        } catch (Exception e) { }
                    }
                    SessionPointer.HandlerInstance.ActiveSession.GetClient(Client.ClientType.Wrapper)?.WE.UpdatePipes(this);
                }
                break;

            case Opcodes.ClientOpcodes.CMSG_GAME_END:
                if (!Initialized)
                {
                    SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_CLIENT_NOT_INITIALIZED));
                    return;
                }
                gs = Functions.GetGameResponse(ClientIdent, payload);
                if (gs == null)
                {
                    SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_INVALID_PACKET,
                                        "Ungültiges GameResponse Format."));
                }
                else
                {
                    if (SessionPointer.GameEndResponses.ContainsKey(ClientIdent))
                    {
                        SessionPointer.GameEndResponses[ClientIdent] = gs;
                    }
                    else
                    {
                        SessionPointer.GameEndResponses.Add(ClientIdent, gs);
                    }
                    SessionPointer.HandlerInstance.SessionEvents.ShowGameFeedback(SessionPointer.ActivePhase);
                }
                break;

            default:
                // Invalid Opcode
                Logging.LogMsg(Logging.LogLevel.WARNING, "Unknown Opcode: {0}, Client: {1}", opcode, ClientIdent);
                SendMsg(GetErrorCmd(Opcodes.ServerOpcodes.SMSG_ERR_UNKNOWN_OPCODE));
                Sessions.CloseSession(ID);
                break;
            }
        }
コード例 #28
0
ファイル: Server.cs プロジェクト: biletnam/VideoSync
        protected override void OnMessage(MessageEventArgs e)
        {
            //Console.WriteLine("Recieved data: " + e.Data);
            var obj = new JavaScriptSerializer().Deserialize(e.Data, typeof(ClientMessage));

            ClientMessage cm = (ClientMessage)obj;

            switch (cm.action)
            {
            //owner requests a time sync
            //the owner's time is sent back to all other clients and set
            //CLIENTSIDE NOTE: clients could use a threshold to determine if it is
            //worth the effort to sync time. ex: if they're within +- 0.02s of owner -- don't sync
            case (int)ACTIONS.SETTIME:
                BroadcastExcept(ACTIONS.BROADCASTTIME, cm.data);
                break;

            //owner requests to set a new url
            //the new url is broadcasted back to all clients except owner
            //CLIENTSIDE NOTE: clients should all set currentTime to 0
            case (int)ACTIONS.SETURL:
                Sessions.Broadcast(ConstructMessage(ACTIONS.BROADCASTURL, cm.data));
                break;

            //Broadcast owner's pause request to all clients
            case (int)ACTIONS.REQUESTPAUSE:
                paused = true;
                BroadcastExcept(ACTIONS.BROADCASTPAUSE, null);
                break;

            //Broadcast owner's pause request to all clients
            case (int)ACTIONS.REQUESTPLAY:
                paused = false;
                BroadcastExcept(ACTIONS.BROADCASTPLAY, null);
                break;

            //Echo chat back to all
            case (int)ACTIONS.SENDCHAT:
                Sessions.Broadcast(ConstructMessage(ACTIONS.BROADCASTCHAT, cm.data));
                break;

            case (int)ACTIONS.DISCONNECTED:
                clientCount--;
                var prevOwner = ownerID;
                Sessions.CloseSession((string)cm.data);

                if ((string)cm.data == prevOwner)
                {
                    Console.WriteLine("Owner disconnected setting new one...");
                    if (Sessions.Count != 0)
                    {
                        TryGetNewOwner();
                    }
                    else
                    {
                        ownerID = "";
                    }
                }
                else
                {
                    Console.WriteLine("Client disconnected.");
                }

                GetCount();
                break;


            case (int)ACTIONS.CLIENTRESPONDTOCOUNT:
                clientCount++;
                Console.WriteLine(clientCount + " clients have responded...");
                break;

            case (int)ACTIONS.CLEARQUEUE:
                Sessions.Broadcast(ConstructMessage(ACTIONS.CLEARQUEUE, null));
                break;

            case (int)ACTIONS.SKIPTOINDEX:
                Sessions.Broadcast(ConstructMessage(ACTIONS.SKIPTOINDEX, cm.data));
                break;

            case (int)ACTIONS.RECIEVEQUEUE:
                Sessions.Broadcast(ConstructMessage(ACTIONS.RECIEVEQUEUE, cm.data));
                break;

            case (int)ACTIONS.OPENROOM:
                Sessions.Broadcast(ConstructMessage(ACTIONS.OPENROOM, null));
                break;
            }
        }