private void OnJoinGameResult(object sender, ClientListener <JoinGameMessage> .TArg e)
        {
            //Получение позиции игрока в игре
            uint?myPlayerPosition = e.Arg.MyPosition;

            //Проверка позиции игрока
            if (myPlayerPosition == null)
            {
                //Если присоединение не удалось, то разрываем соединение
                OnJoin?.Invoke(null);
                tcpClient.Dispose();
                return;
            }

            //Если присоединение успешно
            OnJoin?.Invoke(e.Arg);

            //Если есть противник, то начинаем игру
            if (e.Arg.EnemyName != null)
            {
                joinGameListener.Stop();
                OnStart?.Invoke();
                playGameListener.Start();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Verarbeitet das Betreten eines Users eines Channels
        /// </summary>
        /// <seealso cref="OnJoin"/>
        private void _connection_OnJoin(object sender, JoinEventArgs e)
        {
            Log.Information("{Nickname} hat den Raum {Channel} betreten", e.Who, e.Channel);
            MaintainUser(e.Who);

            ThreadPool.QueueUserWorkItem(x =>
            {
                OnJoin?.Invoke(this, e);
            });
        }
 private void JoinGame(string playerName)
 {
     if (!tcpClient.Connected)
     {
         OnJoin?.Invoke(null);
         return;
     }
     try
     {
         //Отправка имени игрока:
         TextMessage textMessage = new TextMessage(playerName);
         tcpClient.Send(textMessage);
         joinGameListener.Start();
     }
     catch (Exception)
     {
         OnJoin?.Invoke(null);
     }
 }
Exemplo n.º 4
0
        protected void ParseMessage(byte[] bytes)
        {
            if (previousCode == 0)
            {
                byte code = bytes[0];

                if (code == Protocol.JOIN_ROOM)
                {
                    var offset = 1;

                    SessionId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                    offset   += SessionId.Length + 1;

                    SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                    offset      += SerializerId.Length + 1;

                    if (SerializerId == "schema")
                    {
                        serializer = new SchemaSerializer <T>();
                    }
                    else if (SerializerId == "fossil-delta")
                    {
                        serializer = (ISerializer <T>) new FossilDeltaSerializer();
                    }

                    // TODO: use serializer defined by the back-end.
                    // serializer = (Colyseus.Serializer) new FossilDeltaSerializer();

                    if (bytes.Length > offset)
                    {
                        serializer.Handshake(bytes, offset);
                    }

                    if (OnJoin != null)
                    {
                        OnJoin.Invoke(this, new EventArgs());
                    }
                }
                else if (code == Protocol.JOIN_ERROR)
                {
                    var message = System.Text.Encoding.UTF8.GetString(bytes, 2, bytes[1]);
                    OnError.Invoke(this, new ErrorEventArgs(message));
                }
                else if (code == Protocol.LEAVE_ROOM)
                {
                    Leave();
                }
                else
                {
                    previousCode = code;
                }
            }
            else
            {
                if (previousCode == Protocol.ROOM_STATE)
                {
                    SetState(bytes);
                }
                else if (previousCode == Protocol.ROOM_STATE_PATCH)
                {
                    Patch(bytes);
                }
                else if (previousCode == Protocol.ROOM_DATA)
                {
                    var message = MsgPack.Deserialize <object>(new MemoryStream(bytes));
                    OnMessage.Invoke(this, new MessageEventArgs(message));
                }
                previousCode = 0;
            }
        }
Exemplo n.º 5
0
        protected async void ParseMessage(byte[] bytes)
        {
            if (previousCode == 0)
            {
                byte code = bytes[0];

                if (code == Protocol.JOIN_ROOM)
                {
                    var offset = 1;

                    SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                    offset      += SerializerId.Length + 1;

                    if (SerializerId == "schema")
                    {
                        serializer = new SchemaSerializer <T>();
                    }
                    else if (SerializerId == "fossil-delta")
                    {
                        serializer = (ISerializer <T>) new FossilDeltaSerializer();
                    }

                    if (bytes.Length > offset)
                    {
                        serializer.Handshake(bytes, offset);
                    }

                    OnJoin?.Invoke();
                }
                else if (code == Protocol.JOIN_ERROR)
                {
                    var message = System.Text.Encoding.UTF8.GetString(bytes, 2, bytes[1]);
                    OnError?.Invoke(message);
                }
                else if (code == Protocol.ROOM_DATA_SCHEMA)
                {
                    Type messageType = Schema.Context.GetInstance().Get(bytes[1]);

                    var message = (Schema.Schema)Activator.CreateInstance(messageType);
                    message.Decode(bytes, new Schema.Iterator {
                        Offset = 2
                    });

                    OnMessage?.Invoke(message);
                }
                else if (code == Protocol.LEAVE_ROOM)
                {
                    await Leave();
                }
                else
                {
                    previousCode = code;
                }
            }
            else
            {
                if (previousCode == Protocol.ROOM_STATE)
                {
                    SetState(bytes);
                }
                else if (previousCode == Protocol.ROOM_STATE_PATCH)
                {
                    Patch(bytes);
                }
                else if (previousCode == Protocol.ROOM_DATA)
                {
                    var message = MsgPack.Deserialize <object>(new MemoryStream(bytes));
                    OnMessage?.Invoke(message);
                }
                previousCode = 0;
            }
        }
Exemplo n.º 6
0
 void Room_OnJoin(object sender, EventArgs e)
 {
     Debug.Log("Joined room!");
     OnJoin?.Invoke(sender, e);
 }
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            Debug.Log("BYTE =>" + code);

            if (code == Protocol.JOIN_ROOM)
            {
                var offset = 1;

                SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    serializer = new SchemaSerializer <T>();
                }
                else if (SerializerId == "fossil-delta")
                {
                    serializer = (ISerializer <T>) new FossilDeltaSerializer();
                }

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await Connection.Send(new byte[] { Protocol.JOIN_ROOM });
            }
            else if (code == Protocol.ERROR)
            {
                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };
                var errorCode    = Decode.DecodeNumber(bytes, it);
                var errorMessage = Decode.DecodeString(bytes, it);
                OnError?.Invoke((int)errorCode, errorMessage);
            }
            else if (code == Protocol.ROOM_DATA_SCHEMA)
            {
                Type messageType = Schema.Context.GetInstance().Get(bytes[1]);

                var message = (Schema.Schema)Activator.CreateInstance(messageType);
                message.Decode(bytes, new Schema.Iterator {
                    Offset = 2
                });

                IMessageHandler handler = null;
                OnMessageHandlers.TryGetValue("s" + message.GetType(), out handler);

                if (handler != null)
                {
                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogError("room.OnMessage not registered for Schema message: " + message.GetType());
                }
            }
            else if (code == Protocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == Protocol.ROOM_STATE)
            {
                Debug.Log("ROOM_STATE");
                SetState(bytes, 1);
            }
            else if (code == Protocol.ROOM_STATE_PATCH)
            {
                Debug.Log("ROOM_STATE_PATCH");
                Patch(bytes, 1);
            }
            else if (code == Protocol.ROOM_DATA)
            {
                IMessageHandler handler = null;
                object          type;

                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };

                if (Decode.NumberCheck(bytes, it))
                {
                    type = Decode.DecodeNumber(bytes, it);
                    OnMessageHandlers.TryGetValue("i" + type, out handler);
                }
                else
                {
                    type = Decode.DecodeString(bytes, it);
                    OnMessageHandlers.TryGetValue(type.ToString(), out handler);
                }

                if (handler != null)
                {
                    //
                    // MsgPack deserialization can be optimized:
                    // https://github.com/deniszykov/msgpack-unity3d/issues/23
                    //
                    var message = (bytes.Length > it.Offset)
                                                ? MsgPack.Deserialize(handler.Type, new MemoryStream(bytes, it.Offset, bytes.Length - it.Offset, false))
                                                : null;

                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogError("room.OnMessage not registered for: " + type);
                }
            }
        }
Exemplo n.º 8
0
 public void Join()
 {
     OnJoin?.Invoke(this, DateTime.Now);
 }
Exemplo n.º 9
0
 public void HandleJoin()
 {
     OnJoin?.Invoke(this);
 }
Exemplo n.º 10
0
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            if (code == Protocol.JOIN_ROOM)
            {
                var offset = 1;

                SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    serializer = new SchemaSerializer <T>();
                }
//				else if (SerializerId == "fossil-delta")
//				{
//					serializer = (ISerializer<T>) new FossilDeltaSerializer();
//				}

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await Connection.Send(new object[] { Protocol.JOIN_ROOM });
            }
            else if (code == Protocol.JOIN_ERROR)
            {
                var message = System.Text.Encoding.UTF8.GetString(bytes, 2, bytes[1]);
                OnError?.Invoke(message);
            }
            else if (code == Protocol.ROOM_DATA_SCHEMA)
            {
                Type messageType = Schema.Context.GetInstance().Get(bytes[1]);

                var message = (Schema.Schema)Activator.CreateInstance(messageType);
                message.Decode(bytes, new Schema.Iterator {
                    Offset = 2
                });

                OnMessage?.Invoke(message);
            }
            else if (code == Protocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == Protocol.ROOM_STATE)
            {
                SetState(bytes, 1);
            }
            else if (code == Protocol.ROOM_STATE_PATCH)
            {
                Patch(bytes, 1);
            }
            else if (code == Protocol.ROOM_DATA)
            {
                // TODO: de-serialize message with an offset, to avoid creating a new buffer
                var message = MsgPack.Deserialize <object>(new MemoryStream(
                                                               ArrayUtils.SubArray(bytes, 1, bytes.Length - 1)
                                                               ));
                OnMessage?.Invoke(message);
            }
        }
Exemplo n.º 11
0
        public static void TimerElapsed()
        {
            var eventTime = Trim(DateTime.UtcNow);

            try
            {
                List <Downloader.MemberData> membercache;
                if (File.Exists($"{BASE_DIR}/membercache.csv"))
                {
                    membercache = Downloader.ParseMemberData(File.ReadAllText($"{BASE_DIR}/membercache.csv")).ToList();
                }
                else
                {
                    membercache = new List <Downloader.MemberData>();
                }
                string result = Client.GetStringAsync($"http://services.runescape.com/m=clan-hiscores/members_lite.ws?clanName={Downloader.CLAN_NAME}").GetAwaiter().GetResult();
                if (result != null && !result.StartsWith("Clanmate"))
                {
                    return;
                }
                if (result != null && result.Length > 0)
                {
                    File.WriteAllText($"{BASE_DIR}/membercache.csv", result);
                }
                var current = Downloader.ParseMemberData(result).ToList();
                if (membercache.Count > 0 && current.Count > 0)
                {
                    var leave = Downloader.MemberData.Diff(membercache, current);
                    var join  = Downloader.MemberData.Diff(current, membercache);
                    if (leave.Count > 0 && join.Count == 0)
                    {
                        foreach (var leaver in leave)
                        {
                            OnLeave?.Invoke(leaver.Name);
                        }
                    }
                    else if (leave.Count == 0 && join.Count > 0)
                    {
                        foreach (var joiner in join)
                        {
                            OnJoin?.Invoke(joiner.Name);
                        }
                    }
                    else
                    {
                        for (int i = join.Count - 1; i >= 0; i--)
                        {
                            for (int j = leave.Count - 1; j >= 0; j--)
                            {
                                var joiner = join[i];
                                var leaver = leave[j];

                                if (joiner.Rank == leaver.Rank && joiner.ClanXP == leaver.ClanXP && joiner.ClanKills == leaver.ClanKills)
                                {
                                    join.RemoveAt(i);
                                    leave.RemoveAt(j);
                                    OnNamechange?.Invoke(leaver.Name, joiner.Name);
                                    break;
                                }
                            }
                        }

                        if (join.Count > 0)
                        {
                            join.ForEach((item) => OnJoin?.Invoke(item.Name));
                        }
                        if (leave.Count > 0)
                        {
                            leave.ForEach((item) => OnLeave?.Invoke(item.Name));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            if (!Paused && !Updating && (Force || eventTime.Minute % 10 == 0))
            {
                Force    = false;
                Updating = true;
                try
                {
                    var profiles = Downloader.GetProfiles(Client, Downloader.GetClanList(Client));

                    string[] cappers = Downloader.GetCappersList(profiles);

                    var message = new StringBuilder();

                    foreach (var capper in cappers)
                    {
                        if (!CappedList.Contains(capper))
                        {
                            CappedList.Add(capper);
                            if (CappedMessages.Count > 0)
                            {
                                message.Append(string.Format(CappedMessages[Random.Next(0, CappedMessages.Count)], capper) + "\n");
                            }
                        }
                    }

                    if (message.Length > 0 && UpdateChannel != 0)
                    {
                        PostMessageAsync(UpdateChannel, message.ToString()).GetAwaiter().GetResult();
                    }
                    new Thread(() =>
                    {
                        string[] items = Downloader.GetItems(Client, profiles);
                        if (ItemChannel > 0)
                        {
                            try
                            {
                                var builder = new StringBuilder();
                                foreach (var item in items)
                                {
                                    if (builder.Length + item.Length + 1 >= 2000)
                                    {
                                        PostMessageAsync(ItemChannel, builder.ToString()).GetAwaiter().GetResult();
                                        builder.Clear();
                                    }
                                    builder.Append(item);
                                }
                                if (builder.Length > 0)
                                {
                                    PostMessageAsync(ItemChannel, builder.ToString()).GetAwaiter().GetResult();
                                }
                            }
                            catch { }
                        }
                        string[] achievements = Downloader.GetAchievements(Client, profiles);
                        if (AchievementWebhook != null && !Cache)
                        {
                            try
                            {
                                var builder = new StringBuilder();
                                foreach (var achievement in achievements)
                                {
                                    if (builder.Length + achievement.Length + 1 >= 2000)
                                    {
                                        AchievementWebhook.SendMessageAsync(builder.ToString());
                                        builder.Clear();
                                    }
                                    builder.Append(achievement);
                                }
                                if (builder.Length > 0)
                                {
                                    AchievementWebhook.SendMessageAsync(builder.ToString());
                                }
                            }
                            catch { }
                        }
                        Cache = false;
                    }).Start();
                }
                catch (Exception e) { Console.WriteLine(e.Message); }
                CappedList.Sort();
                WriteCookies();
                Updating = false;
                Console.WriteLine(new LogMessage(LogSeverity.Info, "Timer", $"Update finished in {(DateTime.UtcNow - eventTime).TotalMilliseconds}ms."));
            }
            if (eventTime == CurrentResetDate)
            {
                if (ResetChannel != 0)
                {
                    PostMessageAsync(ResetChannel, ResetMessage).GetAwaiter().GetResult();
                }
                if (ListChannel != 0)
                {
                    var      message = new StringBuilder();
                    string[] cappers = CappedList.ToArray();

                    message.Append($"**__Capped citizens for the week of {CurrentResetDate.ToShortDateString()}__**\n");

                    foreach (var capper in cappers)
                    {
                        message.Append($"{capper}\n");
                    }
                    PostMessageAsync(ListChannel, message.ToString()).GetAwaiter().GetResult();
                }
                WriteCookies();
                ProgressDate();
                CappedList.Clear();
            }
        }
        /// <summary>
        ///     The function that will be called when the <see cref="colyseusConnection" /> receives a message
        /// </summary>
        /// <param name="bytes">The message as provided from the <see cref="colyseusConnection" /></param>
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            if (code == ColyseusProtocol.JOIN_ROOM)
            {
                int offset = 1;

                SerializerId = Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    try
                    {
                        serializer = new ColyseusSchemaSerializer <T>();
                    }
                    catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e,
                                                   "Consider using the \"schema-codegen\" and providing the same room state for matchmaking instead of \"" +
                                                   typeof(T).Name + "\"");
                    }
                }
                else if (SerializerId == "fossil-delta")
                {
                    Debug.LogError(
                        "FossilDelta Serialization has been deprecated. It is highly recommended that you update your code to use the Schema Serializer. Otherwise, you must use an earlier version of the Colyseus plugin");
                }
                else
                {
                    try
                    {
                        serializer = (IColyseusSerializer <T>) new ColyseusNoneSerializer();
                    }
                    catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e,
                                                   "Consider setting state in the server-side using \"this.setState(new " + typeof(T).Name +
                                                   "())\"");
                    }
                }

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await colyseusConnection.Send(new[] { ColyseusProtocol.JOIN_ROOM });
            }
            else if (code == ColyseusProtocol.ERROR)
            {
                Iterator it = new Iterator {
                    Offset = 1
                };
                float  errorCode    = Decode.DecodeNumber(bytes, it);
                string errorMessage = Decode.DecodeString(bytes, it);
                OnError?.Invoke((int)errorCode, errorMessage);
            }
            else if (code == ColyseusProtocol.ROOM_DATA_SCHEMA)
            {
                Iterator it = new Iterator {
                    Offset = 1
                };
                float typeId = Decode.DecodeNumber(bytes, it);

                Type          messageType = ColyseusContext.GetInstance().Get(typeId);
                Schema.Schema message     = (Schema.Schema)Activator.CreateInstance(messageType);

                message.Decode(bytes, it);

                IColyseusMessageHandler handler = null;
                OnMessageHandlers.TryGetValue("s" + message.GetType(), out handler);

                if (handler != null)
                {
                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogWarning("room.OnMessage not registered for Schema of type: '" + message.GetType() + "'");
                }
            }
            else if (code == ColyseusProtocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == ColyseusProtocol.ROOM_STATE)
            {
                Debug.Log("ROOM_STATE");
                SetState(bytes, 1);
            }
            else if (code == ColyseusProtocol.ROOM_STATE_PATCH)
            {
                Patch(bytes, 1);
            }
            else if (code == ColyseusProtocol.ROOM_DATA)
            {
                IColyseusMessageHandler handler = null;
                object type;

                Iterator it = new Iterator {
                    Offset = 1
                };

                if (Decode.NumberCheck(bytes, it))
                {
                    type = Decode.DecodeNumber(bytes, it);
                    OnMessageHandlers.TryGetValue("i" + type, out handler);
                }
                else
                {
                    type = Decode.DecodeString(bytes, it);
                    OnMessageHandlers.TryGetValue(type.ToString(), out handler);
                }

                if (handler != null)
                {
                    //
                    // MsgPack deserialization can be optimized:
                    // https://github.com/deniszykov/msgpack-unity3d/issues/23
                    //
                    object message = bytes.Length > it.Offset
                        ? MsgPack.Deserialize(handler.Type,
                                              new MemoryStream(bytes, it.Offset, bytes.Length - it.Offset, false))
                        : null;

                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogWarning("room.OnMessage not registered for: '" + type + "'");
                }
            }
        }
Exemplo n.º 13
0
 public void ProcessJoinCommand(IrcMessage ircMessage)
 {
     OnJoin?.Invoke(Rfc2812Util.UserFromString(ircMessage.From), ircMessage.Target);
 }
Exemplo n.º 14
0
 private void ProcessJoinCommand(string[] tokens)
 {
     OnJoin?.Invoke(Rfc2812Util.UserFromString(tokens[0]), RemoveLeadingColon(tokens[2]));
     //Trace.WriteLine("Join", "IRC");
 }
        /// <summary>
        /// Dequeues all the messages from Discord and invokes appropriate methods. This will process the message and update the internal state before invoking the events. Returns the messages that were invoked and in the order they were invoked.
        /// </summary>
        /// <returns>Returns the messages that were invoked and in the order they were invoked.</returns>
        public IMessage[] Invoke()
        {
            //Dequeue all the messages and process them
            IMessage[] messages = connection.DequeueMessages();
            for (int i = 0; i < messages.Length; i++)
            {
                //Do a bit of pre-processing
                var message = messages[i];
                HandleMessage(message);

                //Invoke the appropriate methods
                switch (message.Type)
                {
                case MessageType.Ready:
                    if (OnReady != null)
                    {
                        OnReady.Invoke(this, message as ReadyMessage);
                    }
                    break;

                case MessageType.Close:
                    if (OnClose != null)
                    {
                        OnClose.Invoke(this, message as CloseMessage);
                    }
                    break;

                case MessageType.Error:
                    if (OnError != null)
                    {
                        OnError.Invoke(this, message as ErrorMessage);
                    }
                    break;

                case MessageType.PresenceUpdate:
                    if (OnPresenceUpdate != null)
                    {
                        OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                    }
                    break;

                case MessageType.Subscribe:
                    if (OnSubscribe != null)
                    {
                        OnSubscribe.Invoke(this, message as SubscribeMessage);
                    }
                    break;

                case MessageType.Unsubscribe:
                    if (OnUnsubscribe != null)
                    {
                        OnUnsubscribe.Invoke(this, message as UnsubscribeMessage);
                    }
                    break;

                case MessageType.Join:
                    if (OnJoin != null)
                    {
                        OnJoin.Invoke(this, message as JoinMessage);
                    }
                    break;

                case MessageType.Spectate:
                    if (OnSpectate != null)
                    {
                        OnSpectate.Invoke(this, message as SpectateMessage);
                    }
                    break;

                case MessageType.JoinRequest:
                    if (OnJoinRequested != null)
                    {
                        OnJoinRequested.Invoke(this, message as JoinRequestMessage);
                    }
                    break;

                case MessageType.ConnectionEstablished:
                    if (OnConnectionEstablished != null)
                    {
                        OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                    }
                    break;

                case MessageType.ConnectionFailed:
                    if (OnConnectionFailed != null)
                    {
                        OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                    }
                    break;

                default:
                    //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                    Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
                    break;
                }
            }

            //Finally, return the messages
            return(messages);
        }
Exemplo n.º 16
0
 private static void RichPresence_OnActivityJoin(string secret)
 {
     OnJoin?.Invoke(secret);
 }
Exemplo n.º 17
0
        protected async void ParseMessage(byte[] bytes)
        {
            byte code = bytes[0];

            if (code == Protocol.JOIN_ROOM)
            {
                var offset = 1;

                SerializerId = System.Text.Encoding.UTF8.GetString(bytes, offset + 1, bytes[offset]);
                offset      += SerializerId.Length + 1;

                if (SerializerId == "schema")
                {
                    try
                    {
                        serializer = new SchemaSerializer <T>();
                    }
                    catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e, "Consider using the \"schema-codegen\" and providing the same room state for matchmaking instead of \"" + typeof(T).Name + "\"");
                    }
                }
                else if (SerializerId == "fossil-delta")
                {
                    try
                    {
                        serializer = (ISerializer <T>) new FossilDeltaSerializer();
                    } catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e, "Consider using \"IndexedDictionary<string, object>\" instead of \"" + typeof(T).Name + "\" for matchmaking.");
                    }
                }
                else
                {
                    try
                    {
                        serializer = (ISerializer <T>) new NoneSerializer();
                    }
                    catch (Exception e)
                    {
                        DisplaySerializerErrorHelp(e, "Consider setting state in the server-side using \"this.setState(new " + typeof(T).Name + "())\"");
                    }
                }

                if (bytes.Length > offset)
                {
                    serializer.Handshake(bytes, offset);
                }

                OnJoin?.Invoke();

                // Acknowledge JOIN_ROOM
                await Connection.Send(new byte[] { Protocol.JOIN_ROOM });
            }
            else if (code == Protocol.ERROR)
            {
                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };
                var errorCode    = Decode.DecodeNumber(bytes, it);
                var errorMessage = Decode.DecodeString(bytes, it);
                OnError?.Invoke((int)errorCode, errorMessage);
            }
            else if (code == Protocol.ROOM_DATA_SCHEMA)
            {
                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };
                var typeId = Decode.DecodeNumber(bytes, it);

                Type messageType = Schema.Context.GetInstance().Get(typeId);
                var  message     = (Schema.Schema)Activator.CreateInstance(messageType);

                message.Decode(bytes, it);

                IMessageHandler handler = null;
                OnMessageHandlers.TryGetValue("s" + message.GetType(), out handler);

                if (handler != null)
                {
                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogWarning("room.OnMessage not registered for Schema of type: '" + message.GetType() + "'");
                }
            }
            else if (code == Protocol.LEAVE_ROOM)
            {
                await Leave();
            }
            else if (code == Protocol.ROOM_STATE)
            {
                Debug.Log("ROOM_STATE");
                SetState(bytes, 1);
            }
            else if (code == Protocol.ROOM_STATE_PATCH)
            {
                Debug.Log("ROOM_STATE_PATCH");
                Patch(bytes, 1);
            }
            else if (code == Protocol.ROOM_DATA)
            {
                IMessageHandler handler = null;
                object          type;

                Schema.Iterator it = new Schema.Iterator {
                    Offset = 1
                };

                if (Decode.NumberCheck(bytes, it))
                {
                    type = Decode.DecodeNumber(bytes, it);
                    OnMessageHandlers.TryGetValue("i" + type, out handler);
                }
                else
                {
                    type = Decode.DecodeString(bytes, it);
                    OnMessageHandlers.TryGetValue(type.ToString(), out handler);
                }

                if (handler != null)
                {
                    //
                    // MsgPack deserialization can be optimized:
                    // https://github.com/deniszykov/msgpack-unity3d/issues/23
                    //
                    var message = (bytes.Length > it.Offset)
                                                ? MsgPack.Deserialize(handler.Type, new MemoryStream(bytes, it.Offset, bytes.Length - it.Offset, false))
                                                : null;

                    handler.Invoke(message);
                }
                else
                {
                    Debug.LogWarning("room.OnMessage not registered for: '" + type + "'");
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Processes the message, updating our internal state and then invokes the events.
        /// </summary>
        /// <param name="message"></param>
        private void ProcessMessage(IMessage message)
        {
            if (message == null)
            {
                return;
            }
            switch (message.Type)
            {
            //We got a update, so we will update our current presence
            case MessageType.PresenceUpdate:
                lock (_sync)
                {
                    PresenceMessage pm = message as PresenceMessage;
                    if (pm != null)
                    {
                        //We need to merge these presences together
                        if (CurrentPresence == null)
                        {
                            CurrentPresence = pm.Presence;
                        }
                        else if (pm.Presence == null)
                        {
                            CurrentPresence = null;
                        }
                        else
                        {
                            CurrentPresence.Merge(pm.Presence);
                        }

                        //Update the message
                        pm.Presence = CurrentPresence;
                    }
                }

                break;

            //Update our configuration
            case MessageType.Ready:
                ReadyMessage rm = message as ReadyMessage;
                if (rm != null)
                {
                    lock (_sync)
                    {
                        Configuration = rm.Configuration;
                        CurrentUser   = rm.User;
                    }

                    //Resend our presence and subscription
                    SynchronizeState();
                }
                break;

            //Update the request's CDN for the avatar helpers
            case MessageType.JoinRequest:
                if (Configuration != null)
                {
                    //Update the User object within the join request if the current Cdn
                    JoinRequestMessage jrm = message as JoinRequestMessage;
                    if (jrm != null)
                    {
                        jrm.User.SetConfiguration(Configuration);
                    }
                }
                break;

            case MessageType.Subscribe:
                lock (_sync)
                {
                    SubscribeMessage sub = message as SubscribeMessage;
                    Subscription |= sub.Event;
                }
                break;

            case MessageType.Unsubscribe:
                lock (_sync)
                {
                    UnsubscribeMessage unsub = message as UnsubscribeMessage;
                    Subscription &= ~unsub.Event;
                }
                break;

            //We got a message we dont know what to do with.
            default:
                break;
            }

            //Invoke the appropriate methods
            switch (message.Type)
            {
            case MessageType.Ready:
                if (OnReady != null)
                {
                    OnReady.Invoke(this, message as ReadyMessage);
                }
                break;

            case MessageType.Close:
                if (OnClose != null)
                {
                    OnClose.Invoke(this, message as CloseMessage);
                }
                break;

            case MessageType.Error:
                if (OnError != null)
                {
                    OnError.Invoke(this, message as ErrorMessage);
                }
                break;

            case MessageType.PresenceUpdate:
                if (OnPresenceUpdate != null)
                {
                    OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                }
                break;

            case MessageType.Subscribe:
                if (OnSubscribe != null)
                {
                    OnSubscribe.Invoke(this, message as SubscribeMessage);
                }
                break;

            case MessageType.Unsubscribe:
                if (OnUnsubscribe != null)
                {
                    OnUnsubscribe.Invoke(this, message as UnsubscribeMessage);
                }
                break;

            case MessageType.Join:
                if (OnJoin != null)
                {
                    OnJoin.Invoke(this, message as JoinMessage);
                }
                break;

            case MessageType.Spectate:
                if (OnSpectate != null)
                {
                    OnSpectate.Invoke(this, message as SpectateMessage);
                }
                break;

            case MessageType.JoinRequest:
                if (OnJoinRequested != null)
                {
                    OnJoinRequested.Invoke(this, message as JoinRequestMessage);
                }
                break;

            case MessageType.ConnectionEstablished:
                if (OnConnectionEstablished != null)
                {
                    OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                }
                break;

            case MessageType.ConnectionFailed:
                if (OnConnectionFailed != null)
                {
                    OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                }
                break;

            default:
                //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
                break;
            }
        }
Exemplo n.º 19
0
        public void Bind(Host host)
        {
            _host = host;
            _host.AddHandler((short)LobbyMessages.RoomCreated, (m, c) => {
                if (RoomCreated != null)
                {
                    var ds        = DataStorage.CreateForRead(m.Body);
                    var roomToken = new Token();
                    roomToken.ReadFromDs(ds);

                    RoomCreated.Invoke(roomToken);
                }
            });
            _host.AddHandler((short)LobbyMessages.PlayerLeaved, (m, c) => {
                if (OnPlayerLeaved != null)
                {
                    var ds          = DataStorage.CreateForRead(m.Body);
                    var playerToken = new Token();
                    playerToken.ReadFromDs(ds);
                    OnPlayerLeaved.Invoke(playerToken);
                }
            });
            _host.AddHandler((short)LobbyMessages.SuccesfullyLeaved, (m, c) => {
                if (OnLeave != null)
                {
                    OnLeave.Invoke();
                }
            });
            _host.AddHandler((short)LobbyMessages.PlayerJoined, (m, c) => {
                if (OnPlayerJoined != null)
                {
                    var ds          = DataStorage.CreateForRead(m.Body);
                    var playerToken = new Token();
                    playerToken.ReadFromDs(ds);
                    OnPlayerJoined.Invoke(playerToken);
                }
            });
            _host.AddHandler((short)LobbyMessages.SuccesfullyJoined, (m, c) => {
                if (OnJoin != null)
                {
                    OnJoin.Invoke();
                }
            });
            _host.AddHandler((short)LobbyMessages.GameStarted, (m, c) => {
                if (OnGameStarted != null)
                {
                    var ds     = DataStorage.CreateForRead(m.Body);
                    _roomToken = new Token();
                    _roomToken.ReadFromDs(ds);
                    OnGameStarted.Invoke();
                }
            });
            _host.AddHandler((short)LobbyMessages.GetRoomsResponse, (m, c) => {
                if (OnRoomInfoRecieved != null)
                {
                    var roomTokens = new List <Token>();
                    roomTokens.FillDeserialize(m.Body);
                    OnRoomInfoRecieved.Invoke(roomTokens);
                }
            });
        }