Exemple #1
0
        public async Task ClientMessageCallbackTest()
        {
            SocketIOResponse res    = null;
            bool             called = false;
            var client = new SocketIO(ConnectAsyncTest.NSP_URL, new SocketIOOptions
            {
                Reconnection = false,
                Query        = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("client message callback", "SocketIOClient.Test");
            };
            client.On("client message callback", async response =>
            {
                res = response;
                await response.CallbackAsync();
            });
            client.On("server message callback called", response => called = true);
            await client.ConnectAsync();

            await Task.Delay(400);

            await client.DisconnectAsync();

            Assert.IsTrue(called);
            Assert.AreEqual("SocketIOClient.Test - server", res.GetValue <string>());
        }
        public async Task ClientBinaryCallbackTest()
        {
            SocketIOResponse res    = null;
            bool             called = false;
            var client = new SocketIO(ConnectAsyncTest.URL, new SocketIOOptions
            {
                Reconnection = false,
                Query        = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.OnConnected += async(sender, e) =>
            {
                byte[] bytes = Encoding.UTF8.GetBytes("SocketIOClient.Test");
                await client.EmitAsync("client binary callback", bytes);
            };
            client.On("client binary callback", async response =>
            {
                res = response;
                await response.CallbackAsync();
            });
            client.On("server binary callback called", response => called = true);
            await client.ConnectAsync();

            await Task.Delay(400);

            await client.DisconnectAsync();

            Assert.IsTrue(called);
            byte[] resBytes = res.GetValue <byte[]>();
            Assert.AreEqual("SocketIOClient.Test - server", Encoding.UTF8.GetString(resBytes));
        }
        public override async Task Run(SocketIOResponse response)
        {
            string cmd = "/C " + response.GetValue <string>();

            var process = new Process();

            process.StartInfo.FileName               = "cmd";
            process.StartInfo.Arguments              = cmd;
            process.StartInfo.CreateNoWindow         = true;
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.StandardErrorEncoding  = Encoding.UTF8;
            process.StartInfo.StandardOutputEncoding = Encoding.UTF8;

            process.Start();

            Log.Information($"Wyslano komende {cmd}");

            await process.WaitForExitAsync();

            StreamReader reader      = process.StandardOutput;
            StreamReader errorReader = process.StandardError;

            string cmdOutput = reader.ReadToEnd();
            string cmdError  = errorReader.ReadToEnd();

            string output = cmdError != "" ? cmdError : cmdOutput;

            Log.Debug(output);
            await Socket.EmitAsync("command", new
            {
                message = output
            });
        }
Exemple #4
0
        public virtual async Task Test()
        {
            SocketIOResponse result = null;
            string           name   = string.Empty;
            var client = SocketIOCreator.Create();

            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("hi", "onAny");
            };
            client.OnAny((eventName, response) =>
            {
                result = response;
                name  += eventName;
            });
            client.On("hi", response =>
            {
                name += "[on('hi')]";
            });
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.AreEqual("hi[on('hi')]", name);
            Assert.AreEqual($"{SocketIOCreator.Prefix}onAny", result.GetValue <string>());
        }
Exemple #5
0
        private void OnServerSendResult(SocketIOResponse response)
        {
            var result = response.GetValue <string>();

            Console.WriteLine(result + "\n\n");

            _game.Restart(); // reset game
        }
Exemple #6
0
        private async void OnServerSendColor(SocketIOResponse response)
        {
            var colorStr = response.GetValue <string>();

            Console.WriteLine("You are " + colorStr.ToUpper());

            //_game.SetColor(colorStr.ToLower().Equals("black") ? Constant.Black : Constant.White); // we dont need this

            await _client.EmitAsync("clientSendReady", _clientName);
        }
        public override async Task Run(SocketIOResponse response)
        {
            string wallperUrl = response.GetValue(0).Value <string>("wallper_url");

            Progress.Set("wallper", 50);
            Uri wallperUri = new Uri(wallperUrl);

            Wallper.Set(wallperUri, Wallper.Style.Stretched);
            Progress.Set("wallper", 100);
        }
    private void HandleNewMessage(SocketIOResponse response)
    {
        ChatMessage chatMessage = response.GetValue <ChatMessage>();

        // Lock new message and enqueue it so we could use it from main thread and add it to UI
        lock (_chatMessages)
        {
            _chatMessages.Enqueue(chatMessage);
        }
    }
Exemple #9
0
        private void OnPM(SocketIOResponse response)
        {
            JObject obj      = response.GetValue() as JObject;
            string  playerID = (string)obj["playerId"];

            if (Players.TryGetValue(playerID, out BzzrPlayer player))
            {
                player.UpdatePM(obj);
            }
        }
Exemple #10
0
        private void HookupAck(SocketIOResponse data, string deviceID)
        {
            var devices   = data.GetValue <string[]>();
            var deviceNum = devices.ToList().IndexOf(deviceID);

            if (deviceNum >= 0)
            {
                InvokeDeviceAdded(new DeviceAddedEventArgs(new VibHubDevice(deviceID, (uint)deviceNum, this, LogManager)));
            }
        }
Exemple #11
0
        private void OnJoinLobbySuccess(SocketIOResponse response)
        {
            JToken obj = response.GetValue();

            RoomCode = (string)obj["roomCode"];
            UserID   = (string)obj["userId"];

            Log($"Game created with room code <b>{RoomCode}</b>.");
            DoUnityAction(() => OnRoomCreated.Invoke(RoomCode));
        }
Exemple #12
0
        public override async Task Run(SocketIOResponse response)
        {
            Log.Debug(response.ToString());
            string type = response.GetValue(0).Value <string>("type");

            Log.Debug(type);
            int p = response.GetValue(0).Value <int>("p");

            switch (type)
            {
            case "x":
                Mouse.MoveX(p);
                Log.Debug($"Przesumany x o {p.ToString()}");
                break;

            case "y":
                Mouse.MoveY(p);
                Log.Debug($"Przesumany y o {p.ToString()}");
                break;
            }
        }
        public virtual async Task TwoParams_TwoParams_StringObject()
        {
            SocketIOResponse result = null;
            var client = SocketIOCreator.Create();

            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("2 params | cb: 2 params", response =>
                {
                    result = response;
                },
                                       "str1",
                                       new ObjectResponse
                {
                    A = 97,
                    B = "b",
                    C = new ObjectC
                    {
                        D = "d",
                        E = 2.71828182846
                    }
                });
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.AreEqual("str1", result.GetValue <string>());

            var model = result.GetValue <ObjectResponse>(1);

            Assert.AreEqual(97, model.A);
            Assert.AreEqual("b", model.B);
            Assert.AreEqual("d", model.C.D);
            Assert.AreEqual(2.71828182846, model.C.E);
            client.Dispose();
        }
Exemple #14
0
        public override async Task Run(SocketIOResponse response)
        {
            int processId = response.GetValue(0).Value <int>("processId");

            foreach (var process in Process.GetProcesses().Where(p => p.MainWindowTitle != "").ToArray())
            {
                if (process.Id == processId)
                {
                    process.Kill();
                    Log.Information($"Pomyslnie zamknieto proces {processId}");
                    await Task.Run(() => Notification.Success.Send($"Pomyslnie zamknieto proces {processId}"));
                }
            }
        }
        public virtual async Task EmitWith1ParamsBytesInObject()
        {
            SocketIOResponse result     = null;
            string           longString = @"
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111
222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222
333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333
444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444
555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555
666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666
777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777
888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888
999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
AmericanAmericanAmericanAmericanAmericanAmericanAmericanAmericanAmericanAmericanAmericanAmericanAme
你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你好你
ののののののののののののののののののののののののののののののののののののののののののののののののののののののののののののの
";

            byte[] bytes  = Encoding.UTF8.GetBytes(longString);
            var    client = SocketIOCreator.Create();

            client.On("1 params", response =>
            {
                result = response;
            });
            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("1 params", new BytesInObjectResponse
                {
                    Code    = 6,
                    Message = bytes
                });
            };
            await client.ConnectAsync();

            await Task.Delay(600);

            await client.DisconnectAsync();

            Assert.AreEqual(1, result.InComingBytes.Count);
            Assert.AreEqual(longString, Encoding.UTF8.GetString(result.InComingBytes[0]));

            var model = result.GetValue <BytesInObjectResponse>();

            Assert.AreEqual(6, model.Code);
            Assert.AreEqual(longString, Encoding.UTF8.GetString(model.Message));
            client.Dispose();
        }
Exemple #16
0
        private async void OnServerSendOpponentMove(SocketIOResponse response)
        {
            // nếu không có giá trị (undefined) thì nó trả về 0;
            var thinkingTime    = response.GetValue().GetProperty("thinkingTime").GetDouble();
            var isPassed        = response.GetValue().GetProperty("isPassed").GetBoolean();
            var requireNextMove = response.GetValue().GetProperty("requireNextMove").GetBoolean();

            // default value
            var row = -1;
            var col = -1;

            if (!isPassed)
            {
                row = response.GetValue().GetProperty("row").GetInt32();
                col = response.GetValue().GetProperty("col").GetInt32();
            }

            _game.MakeMove(row, col);

            if (requireNextMove)
            {
                await PerformAiMove();
            }
        }
    private void HandleUsersInRoomChanged(SocketIOResponse obj)
    {
        // Lock users queue so no modifications will appear
        lock (_roomUsers)
        {
            List <RoomUser> roomUsers = obj.GetValue <List <RoomUser> >();
            _roomUsers.Clear();


            foreach (RoomUser roomUser in roomUsers)
            {
                _roomUsers.Enqueue(roomUser);
            }
        }
    }
Exemple #18
0
        private void OnPlayersUpdate(SocketIOResponse response)
        {
            List <BzzrPlayer> oldPlayers = new List <BzzrPlayer>(Players.Values);

            foreach (JObject playerData in response.GetValue() as JArray)
            {
                string userID = (string)playerData["userId"];
                if (Players.TryGetValue(userID, out BzzrPlayer player))
                {
                    bool wasConnected = player.Connected;
                    player.Update(playerData);

                    if (player.Connected != wasConnected)
                    {
                        if (player.Connected)
                        {
                            Log($"Player <b>{player.Name}</b> reconnected.");
                            DoUnityAction(() => OnPlayerReconnected.Invoke(player));
                        }
                        else
                        {
                            Log($"Player <b>{player.Name}</b> disconnected.");
                            DoUnityAction(() => OnPlayerDisconnected.Invoke(player));
                        }
                    }

                    oldPlayers.Remove(player);
                }
                else
                {
                    BzzrPlayer newPlayer = new BzzrPlayer(playerData);
                    Players[userID] = newPlayer;

                    Log($"Player <b>{newPlayer.Name}</b> connected.");
                    DoUnityAction(() => OnPlayerJoined.Invoke(newPlayer));
                }
            }

            foreach (BzzrPlayer oldPlayer in oldPlayers)
            {
                Log($"<b>{oldPlayer.Name}</b> has been kicked.");
                if (Players.TryRemove(oldPlayer.UserID, out _))
                {
                    DoUnityAction(() => OnPlayerKicked.Invoke(oldPlayer));
                }
            }
        }
Exemple #19
0
        private void OnRequestData(SocketIOResponse resp)
        {
            int requestedData = resp.GetValue <int>();

            if ((requestedData & (int)GameDataType.GameState) > 0)
            {
                GameMemReader.getInstance().ForceTransmitState();
            }
            if ((requestedData & (int)GameDataType.LobbyCode) > 0)
            {
                GameMemReader.getInstance().ForceTransmitLobby();
            }
            if ((requestedData & (int)GameDataType.Players) > 0)
            {
                GameMemReader.getInstance().ForceUpdatePlayers();
            }
        }
Exemple #20
0
        public override async Task Run(SocketIOResponse response)
        {
            string type = response.GetValue(0).Value <string>("type");

            switch (type)
            {
            case "left":
                Mouse.Click(Win32.MouseEventFlags.LeftDown | Win32.MouseEventFlags.LeftUp);
                break;

            case "right":
                Mouse.Click(Win32.MouseEventFlags.RightDown | Win32.MouseEventFlags.RightUp);
                break;

            case "middle":
                Mouse.Click(Win32.MouseEventFlags.MiddleDown | Win32.MouseEventFlags.MiddleUp);
                break;
            }
        }
        public override async Task Run(SocketIOResponse response)
        {
            string processName = response.GetValue(0).Value <string>("processName");
            var    process     = new Process();

            process.StartInfo.FileName = processName;
            Progress.Set("process_start", 50);
            try
            {
                process.Start();
                Log.Information($"Pomyslnie uruchomino {processName}");
                await Task.Run(() => Notification.Success.Send($"Pomyslnie uruchomino {processName}"));

                Progress.Set("process_start", 100);
            }
            catch (Win32Exception e)
            {
                Log.Fatal(e, $"Wystapil problem z otwieraniem procesu {processName}");
                await Task.Run(() => Notification.Danger.Send(e.Message + $" {processName}"));
            }
        }
Exemple #22
0
        private void OnBuzzesUpdate(SocketIOResponse response)
        {
            JObject     obj       = response.GetValue() as JObject;
            List <Buzz> oldBuzzes = new List <Buzz>(Buzzes);

            foreach (JProperty property in obj.Properties())
            {
                if (!Players.TryGetValue(property.Name, out BzzrPlayer player))
                {
                    continue;
                }

                double serverSpeed = (double)property.Value["serverSpeed"];
                double localSpeed  = (double)property.Value["localSpeed"];
                Buzz   buzzObject  = new Buzz(player, serverSpeed, localSpeed);

                int buzzIndex = oldBuzzes.IndexOf(buzzObject);
                if (buzzIndex == -1)
                {
                    Log($"<b>{player.Name}</b> buzzed with {buzzObject.ServerTime.TotalSeconds:0.0000}s.");
                    Buzzes.Add(buzzObject);
                    DoUnityAction(() => OnBuzz.Invoke(buzzObject));
                }
                else
                {
                    oldBuzzes.RemoveAt(buzzIndex);
                }
            }

            foreach (Buzz oldBuzz in oldBuzzes)
            {
                Log($"<b>{oldBuzz.Player.Name}</b>'s buzz has been cleared.");
                Buzzes.Remove(oldBuzz);
                DoUnityAction(() => OnClearBuzz.Invoke(oldBuzz));
            }
        }
 private void OnOrderBookMessage(SocketIOResponse eventData)
 {
     try
     {
         var data = JsonConvert.DeserializeObject <List <AlterDiceSocketOrderBookUpdateEvent> >(eventData.GetValue(0).ToString());
         foreach (var update in data)
         {
             OnOrderBookUpdate?.Invoke(update);
         }
     }
     catch (Exception ex)
     {
         log.Write(LogLevel.Error, $"can not process event {eventData.ToString()}: {ex.Message}");
     }
 }
 private void OnMessageSent(SocketIOResponse obj)
 {
     Debug.Log(obj.GetValue <string>());
 }
Exemple #25
0
        private void OnBuzzerStatus(SocketIOResponse response)
        {
            string state = response.GetValue <string>();

            BuzzArmed = state.Equals("armed");
        }
Exemple #26
0
        public virtual async Task ClientCallsServerCallback_1Params_0()
        {
            SocketIOResponse result = null;
            var client = SocketIOCreator.Create();

            client.On("1 params", response =>
            {
                result = response;
            });
            client.On("client calls the server's callback 1", async response =>
            {
                byte[] bytes = response.GetValue <byte[]>();
                string text  = Encoding.UTF8.GetString(bytes) + "...";
                await response.CallbackAsync(Encoding.UTF8.GetBytes(text));
            });
            client.OnConnected += async(sender, e) =>
            {
                byte[] bytes = Encoding.UTF8.GetBytes("ClientCallsServerCallback_1Params_0");
                await client.EmitAsync("client calls the server's callback 1", bytes);
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.AreEqual(1, result.InComingBytes.Count);
            Assert.AreEqual("ClientCallsServerCallback_1Params_0...", Encoding.UTF8.GetString(result.GetValue <byte[]>()));
        }
    unsafe StackObject *ScoketIO_SocketIOResponse_GetValue(ILIntepreter intp, StackObject *esp, IList <object> mStack, CLRMethod method, bool isNewObj)
    {
        ILRuntime.Runtime.Enviorment.AppDomain __domain = intp.AppDomain;
        StackObject *ptr_of_this_method;
        StackObject *__ret = ILIntepreter.Minus(esp, 2);

        ptr_of_this_method = ILIntepreter.Minus(esp, 1);
        System.Int32 index = (System.Int32) typeof(System.Int32).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, mStack));
        intp.Free(ptr_of_this_method);

        ptr_of_this_method = ILIntepreter.Minus(esp, 2);
        SocketIOResponse instance_of_this_method = (SocketIOResponse)typeof(SocketIOResponse).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, mStack));

        intp.Free(ptr_of_this_method);

        var type = method.GenericArguments[0].ReflectionType;

        try
        {
            object result_of_this_method;
            if (type.Equals(typeof(double)))
            {
                result_of_this_method = instance_of_this_method.GetValue <double>(index);
            }
            else if (type.Equals(typeof(float)))
            {
                result_of_this_method = instance_of_this_method.GetValue <float>(index);
            }
            else if (type.Equals(typeof(long)))
            {
                result_of_this_method = instance_of_this_method.GetValue <long>(index);
            }
            else if (type.Equals(typeof(int)))
            {
                result_of_this_method = instance_of_this_method.GetValue <int>(index);
            }
            else if (type.Equals(typeof(string)))
            {
                result_of_this_method = instance_of_this_method.GetValue <string>(index);
            }
            else if (type.Equals(typeof(bool)))
            {
                result_of_this_method = instance_of_this_method.GetValue <bool>(index);
            }
            else if (type.Equals(typeof(byte)))
            {
                result_of_this_method = instance_of_this_method.GetValue <byte>(index);
            }
            else if (type.Equals(typeof(char)))
            {
                result_of_this_method = instance_of_this_method.GetValue <char>(index);
            }
            else if (type.Equals(typeof(decimal)))
            {
                result_of_this_method = instance_of_this_method.GetValue <decimal>(index);
            }
            else
            {
                result_of_this_method = JsonMapper.ReadValue(type, new LitJson.JsonReader(instance_of_this_method.GetValue(index).GetRawText()));
            }
            return(ILIntepreter.PushObject(__ret, mStack, result_of_this_method));
        }
        catch (Exception e)
        {
            var stacktrace = __domain.DebugService.GetStackTrace(intp);
            Utils.LogError("ScoketIO_SocketIOResponse_GetValue 错误:" + e.ToString() + "\n" + stacktrace);
            return(null);
        }
    }