Exemple #1
0
 public void Init(string token)
 {
     _socketIo = new SocketIO("wss://sockets.streamlabs.com")
     {
         Parameters = new Dictionary <string, string>
         {
             { "token", token }
         }
     };
     _socketIo.OnConnected += () => _baseDataHandler.Logger.WriteLine("Connected to Streamlabs");
     _socketIo.OnClosed    += OnSocketClosed;
     _socketIo.On("event", args =>
     {
         try
         {
             _baseDataHandler.Logger.WriteLine("Message: " + args.Text);
             OnSocketMessage(args.Text);
         }
         catch (Exception e)
         {
             _baseDataHandler.Logger.WriteLine(e);
         }
     });
     _socketIo.ConnectAsync();
     _running = true;
 }
Exemple #2
0
        public void Unpack(SocketIO client, string text)
        {
            int index = text.IndexOf('-');

            if (index > 0)
            {
                if (int.TryParse(text.Substring(0, index), out _totalCount))
                {
                    text = text.Substring(index + 1);
                    if (!string.IsNullOrEmpty(client.Namespace))
                    {
                        text = text.Substring(client.Namespace.Length);
                    }
                    int    packetIndex = text.IndexOf('[');
                    string id          = null;
                    if (packetIndex > 0)
                    {
                        id   = text.Substring(0, index);
                        text = text.Substring(index);
                    }
                    _array    = JArray.Parse(text);
                    EventName = _array[0].ToString();
                    _array.RemoveAt(0);
                    Response = new SocketIOResponse(_array, client);
                    if (int.TryParse(id, out int packetId))
                    {
                        Response.PacketId = packetId;
                    }
                    client.OnBytesReceived += Client_OnBytesReceived;
                }
            }
        }
Exemple #3
0
        //TODO ADD AN OPTION TO SKIP VIEWING MATCHES AND GO STRAIGHT TO SELECTING LIVE MATCHES.
        //TO BE USED AFTER EXITING WATCHING A LIVE MATCH SO THEY CAN IMMEDIATELY CHOOSE AGAIN.

        public async void Watch(string matchID, string scorebotURL = "")
        {
            //scoreboard+log is 84x28. for the love of god do not use a resolution lower than that
            SocketIO client = SetupSIOClient(matchID, scorebotURL);

            await StartSocketAsync(client);
        }
 protected void Init(Dictionary <string, string> parameters)
 {
     _socketIo = new SocketIO(Url, new SocketIOOptions
     {
         Query = parameters,
         EnabledSslProtocols = (SslProtocols)12288 | SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls
     });
     _socketIo.OnConnected    += (sender, e) => _plugin.Logger.WriteLine($"Connected to {Name}");
     _socketIo.OnDisconnected += OnSocketClosed;
     _socketIo.OnError        += (sender, args) =>
     {
         _plugin.ConnectionError(Name, args);
         _plugin.Logger.WriteLine(args);
         _socketIo.DisconnectAsync();
     };
     foreach (var s in Event)
     {
         _socketIo.On(s, args =>
         {
             try
             {
                 var jObject = args.GetValue <JObject>();
                 _plugin.Logger.WriteLine("Event: " + s + ", Message: " + jObject.ToString(Formatting.None));
                 OnSocketMessage(s, jObject);
             }
             catch (Exception e)
             {
                 _plugin.Logger.WriteLine(e);
             }
         });
     }
     _running = true;
     Connect();
 }
Exemple #5
0
        public void Connect(string url, string paramGuildID)
        {
            GuildID = paramGuildID;
            socket  = new SocketIO(url);

            /*socket.On("hi", response =>
             * {
             *  string text = response.GetValue<string>();
             * });*/
            socket.OnConnected += (sender, e) =>
            {
                GameMemReader.getInstance().GameStateChanged += GameStateChangedHandler;
                GameMemReader.getInstance().PlayerChanged    += PlayerChangedHandler;
                UpdateGuildID(paramGuildID, false);
            };

            socket.ConnectAsync();

            while (true)
            {
                string[] command = Console.ReadLine().Split();
                if (command.Length > 1 && command[0] == "setid")
                {
                    UpdateGuildID(command[1]);
                }
            }
        }
Exemple #6
0
        private async void GetLiveEntry(string hint)
        {
            Console.Write(hint);
            string liveEntry = Console.ReadLine().ToLower().Trim();

            if (liveEntry == "q")
            {
                Environment.Exit(0);
            }
            else if (liveEntry == "l")
            {
                Reset(live: false);
                return;
            }
            else if (liveEntry == "r")
            {
                Reset(live: true);
                return;
            }

            //if doesn't match any valid input
            else if (!int.TryParse(liveEntry, out _) || liveEntry == "b")
            {
                GetLiveEntry(hint);
            }
            else
            {
                int      index     = int.Parse(liveEntry) - 1;
                string[] matchInfo = (string[])this.liveMatchIDs[index];
                Console.WriteLine("So you decided to watch: " + matchInfo[1]);
                SocketIO client = SetupSIOClient(matchInfo[0]);
                await StartSocketAsync(client);
            }
        }
        public async Task CancelTextMessageTest()
        {
            string result = null;
            var    client = new SocketIO(ConnectAsyncTest.URL, new SocketIOOptions
            {
                Reconnection = false,
                Query        = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.On("hi", response =>
            {
                result = response.GetValue <string>();
            });
            client.OnConnected += async(sender, e) =>
            {
                var cts = new CancellationTokenSource();
                cts.Cancel();
                await client.EmitAsync("hi", cts.Token, ".net core");
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.IsNull(result);
        }
        public async Task CancelBinaryMessageTest()
        {
            string result = null;
            var    client = new SocketIO(ConnectAsyncTest.URL, new SocketIOOptions
            {
                Reconnection = false,
                Query        = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.On("binary", response =>
            {
                var bytes = response.GetValue <byte[]>();
                result    = Encoding.UTF8.GetString(bytes);
            });
            client.OnConnected += async(sender, e) =>
            {
                var cts = new CancellationTokenSource();
                cts.Cancel();
                await client.EmitAsync("binary", cts.Token, "return all the characters");
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.IsNull(result);
        }
 public void Dispose()
 {
     try
     {
         if (keepAliveTimer != null)
         {
             keepAliveTimer.Elapsed -= OnTimedEvent;
             keepAliveTimer          = null;
         }
         //await socket.DisconnectAsync();
         if (socket != null)
         {
             monitorURIList.Clear();
             OnEvent                = null;
             socket.OnConnected    -= Socket_OnConnected;
             socket.OnDisconnected -= Socket_OnDisconnected;
             socket = null;
         }
     }
     catch (Exception ex)
     {
         VoicenterRealtimeLogger logger = new VoicenterRealtimeLogger();
         logger.ex      = ex;
         logger.message = $" in Dispose() method, socket {socket?.ServerUri}";
         logger.level   = LogLevel.Error;
         Logger.log(this, logger);
     }
 }
        public async Task AckTest()
        {
            JToken result = null;
            var    client = new SocketIO(ConnectAsyncTest.URL, new SocketIOOptions
            {
                Reconnection = false,
                Query        = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("ack", response =>
                {
                    result = response.GetValue();
                }, ".net core");
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.IsTrue(result.Value <bool>("result"));
            Assert.AreEqual("ack(.net core)", result.Value <string>("message"));
        }
        public virtual async Task Test()
        {
            bool   connected = false;
            string error     = null;
            var    client    = new SocketIO(SocketIOCreator.Url, new SocketIOOptions
            {
                Reconnection = false,
                EIO          = SocketIOCreator.EIO
            });

            client.OnConnected += (sender, e) => connected = true;
            client.OnError     += (sender, e) => error = e;
            await client.ConnectAsync();

            await Task.Delay(600);

            Assert.IsFalse(client.Connected);
            Assert.IsTrue(client.Disconnected);

            await client.DisconnectAsync();

            Assert.IsFalse(client.Connected);
            Assert.IsTrue(client.Disconnected);
            Assert.IsFalse(connected);
            Assert.AreEqual("Authentication error", error);
            client.Dispose();
        }
Exemple #12
0
        public async Task Emit3StringTest()
        {
            var client = new SocketIO("http://localhost:3000");

            var dic = new Dictionary <int, bool>();

            for (int i = 0; i < 3; i++)
            {
                dic.Add(i, false);
            }

            client.On("test", res =>
            {
                string text = JsonConvert.DeserializeObject <string>(res.Text);
                int id      = int.Parse(text[0].ToString());
                dic[id]     = true;
            });

            await client.ConnectAsync();

            await Task.Delay(1000);

            foreach (var item in dic)
            {
                await client.EmitAsync("test", item.Key.ToString());
            }
            await Task.Delay(1000);

            await client.CloseAsync();

            Assert.IsTrue(dic.All(i => i.Value));
        }
        public async Task IOConnectAsync(SocketIO io)
        {
            var builder = new StringBuilder();

            builder.Append("40");

            if (!string.IsNullOrEmpty(io.Namespace))
            {
                builder.Append(io.Namespace.TrimEnd(','));
            }
            if (io.Options.Query != null && io.Options.Query.Count > 0)
            {
                builder.Append('?');
                int index = -1;
                foreach (var item in io.Options.Query)
                {
                    index++;
                    builder
                    .Append(item.Key)
                    .Append('=')
                    .Append(item.Value);
                    if (index < io.Options.Query.Count - 1)
                    {
                        builder.Append('&');
                    }
                }
            }
            if (!string.IsNullOrEmpty(io.Namespace))
            {
                builder.Append(',');
            }
            await io.Socket.SendMessageAsync(builder.ToString());
        }
Exemple #14
0
        public async Task CloseByClientTest()
        {
            bool result = false;
            var  client = new SocketIO("http://localhost:3000");

            client.OnClosed += reason =>
            {
                if (reason == ServerCloseReason.ClosedByClient)
                {
                    result = true;
                }
                else
                {
                    Assert.Fail();
                }
            };
            await client.ConnectAsync();

            await Task.Delay(1000);

            await client.CloseAsync();

            await Task.Delay(1000);

            Assert.IsTrue(result);
        }
Exemple #15
0
        public async Task BinaryTest()
        {
            string result = null;
            var    client = new SocketIO(ConnectAsyncTest.NSP_URL, new SocketIOOptions
            {
                Reconnection = false,
                Query        = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.On("binary", response =>
            {
                var bytes = response.GetValue <byte[]>();
                result    = Encoding.UTF8.GetString(bytes);
            });
            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("binary", "return all the characters");
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.AreEqual("return all the characters", result);
        }
Exemple #16
0
        private void buttonReg_Click(object sender, EventArgs e)
        {
            connectToServer();
            if (!Data.connectedToServer)
            {
                MessageBox.Show("Can't connect to server!", "Error", MessageBoxButtons.OK);
            }


            if (Data.connectedToServer)
            {
                if (!Data.listenerStarted)
                {
                    Thread thr = new Thread(this.socketListener);
                    thr.Start();
                }

                SocketIO.SendAll(
                    Data.serverSocket,
                    CmdPrefix.registerCommandPrefix + SocketIO.Serialize(
                        new UserDescriptor(this.inputName.Text, this.inputPassword.Text)
                        )
                    );
            }
        }
        public void Unpack(SocketIO client, string text)
        {
            int index = text.IndexOf('-');

            if (index > 0)
            {
                if (int.TryParse(text.Substring(0, index), out _totalCount))
                {
                    text = text.Substring(index + 1);
                    if (!string.IsNullOrEmpty(client.Namespace))
                    {
                        text = text.Substring(client.Namespace.Length);
                    }
                    int packetIndex = text.IndexOf('[');
                    if (int.TryParse(text.Substring(0, packetIndex), out _packetId))
                    {
                        string data = text.Substring(packetIndex);
                        _array = JArray.Parse(data);
                        if (client.Acks.ContainsKey(_packetId))
                        {
                            _response = new SocketIOResponse(_array);
                            client.OnBytesReceived += Client_OnBytesReceived;
                        }
                    }
                }
            }
        }
Exemple #18
0
        public async Task EventAckTest()
        {
            JsonElement result = new JsonElement();
            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("ack", response =>
                {
                    result = response.GetValue();
                }, ".net core");
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.IsTrue(result.GetProperty("result").GetBoolean());
            Assert.AreEqual("ack(.net core)", result.GetProperty("message").GetString());
        }
Exemple #19
0
        public async Task EventHiTest()
        {
            string result = null;
            var    client = new SocketIO(ConnectAsyncTest.NSP_URL, new SocketIOOptions
            {
                Reconnection = false,
                Query        = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.On("hi", response =>
            {
                result = response.GetValue <string>();
            });
            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("hi", ".net core");
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.AreEqual("hi .net core, You are connected to the server - nsp", result);
        }
Exemple #20
0
        public async Task MessageEventBinaryTest()
        {
            var          client = new SocketIO("http://localhost:3000");
            string       guid = Guid.NewGuid().ToString();
            ResponseArgs arg0 = null, arg1 = null, arg2 = null;

            client.On("message send", res => arg0 = res, res => arg1 = res, res => arg2 = res);
            await client.ConnectAsync();

            await Task.Delay(1000);

            await client.EmitAsync("message send", guid);

            await Task.Delay(1000);

            await client.CloseAsync();

            Assert.AreEqual(2, arg0.Buffers.Count);
            Assert.AreEqual(2, arg1.Buffers.Count);
            Assert.AreEqual(2, arg2.Buffers.Count);
            Assert.AreEqual("message send buffer string " + guid, Encoding.UTF8.GetString(arg0.Buffers[0]));
            Assert.AreEqual("message send buffer string " + guid, Encoding.UTF8.GetString(arg0.Buffers[1]));
            Assert.AreEqual("message send buffer string " + guid, Encoding.UTF8.GetString(arg1.Buffers[0]));
            Assert.AreEqual("message send buffer string " + guid, Encoding.UTF8.GetString(arg1.Buffers[1]));
            Assert.AreEqual("message send buffer string " + guid, Encoding.UTF8.GetString(arg2.Buffers[0]));
            Assert.AreEqual("message send buffer string " + guid, Encoding.UTF8.GetString(arg2.Buffers[1]));
            Assert.AreEqual("{\"_placeholder\":true,\"num\":0}", arg0.Text);
            Assert.AreEqual("string", JsonConvert.DeserializeObject <string>(arg1.Text));
            Assert.AreEqual("{\"data\":{\"_placeholder\":true,\"num\":1}}", arg2.Text);
        }
Exemple #21
0
        public void Unpack(SocketIO client, string text)
        {
            if (!string.IsNullOrEmpty(client.Namespace) && text.StartsWith(client.Namespace))
            {
                text = text.Substring(client.Namespace.Length);
            }
            int    index = text.IndexOf('[');
            string id    = null;

            if (index > 0)
            {
                id   = text.Substring(0, index);
                text = text.Substring(index);
            }
            var array = JsonDocument.Parse(text).RootElement.EnumerateArray().ToList();

            EventName = array[0].GetString();
            array.RemoveAt(0);
            Response = new SocketIOResponse(array, client);
            if (int.TryParse(id, out int packetId))
            {
                Response.PacketId = packetId;
            }
            if (client.Handlers.ContainsKey(EventName))
            {
                client.Handlers[EventName](Response);
            }
            OnEnd();
        }
Exemple #22
0
        public async Task OnReceivedEventTest()
        {
            ReceivedEventArgs args = null;
            var client             = new SocketIO(Uri, new SocketIOOptions
            {
                Query = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("hi", "unit test");
            };
            client.OnReceivedEvent += (sender, e) => args = e;
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.AreEqual("hi", args.Event);
            Assert.AreEqual("hi unit test, You are connected to the server", args.Response.GetValue <string>());
        }
Exemple #23
0
 public void Init(string token)
 {
     _socketIo = new SocketIO("wss://seapi.gorymoon.se/")
     {
         Parameters = new Dictionary <string, string>
         {
             { "token", token }
         }
     };
     _socketIo.OnConnected += () => _baseDataHandler.Logger.WriteLine("Connected to Twitch Extension");
     _socketIo.OnClosed    += OnSocketClosed;
     _socketIo.On("action", args =>
     {
         try
         {
             _baseDataHandler.Logger.WriteLine("Message: " + args.Text);
             OnSocketMessage(args.Text);
         }
         catch (Exception e)
         {
             _baseDataHandler.Logger.WriteLine(e);
         }
     });
     _socketIo.ConnectAsync();
     _running = true;
 }
Exemple #24
0
        public async Task MessageEventBinaryPathTest()
        {
            var          client = new SocketIO("http://localhost:3000/path");
            string       guid   = Guid.NewGuid().ToString();
            ResponseArgs arg0   = null;

            client.On("message send", res => arg0 = res);
            await client.ConnectAsync();

            await Task.Delay(1000);

            await client.EmitAsync("message send", guid);

            await Task.Delay(1000);

            Assert.AreEqual(1, arg0.Buffers.Count);
            Assert.AreEqual("message send buffer string", Encoding.UTF8.GetString(arg0.Buffers[0]));

            await Task.Delay(1000);

            await client.EmitAsync("message send", guid);

            Assert.AreEqual(1, arg0.Buffers.Count);
            Assert.AreEqual("message send buffer string", Encoding.UTF8.GetString(arg0.Buffers[0]));

            await client.CloseAsync();
        }
        public async Task NspHiTest()
        {
            string result = null;
            var    client = new SocketIO(ConnectAsyncTest.V4_NSP_URL, new SocketIOOptions
            {
                Reconnection = false,
                EIO          = 4,
                Query        = new Dictionary <string, string>
                {
                    { "token", "v4" }
                }
            });

            client.On("hi", response =>
            {
                result = response.GetValue <string>();
            });
            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("hi", "socket.io v3");
            };
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.AreEqual("nsp: socket.io v3", result);
        }
Exemple #26
0
        public async Task RoomMessageTest()
        {
            string room       = "ROOM";
            string client1Msg = string.Empty;
            string client2Msg = string.Empty;

            var client1 = new SocketIO("http://localhost:3000");

            client1.On(room, res => client1Msg = res.Text);
            await client1.ConnectAsync();

            await Task.Delay(1000);

            await client1.EmitAsync("create room", room);

            var client2 = new SocketIO("http://localhost:3000");

            client2.On(room, res => client2Msg = res.Text);
            await client2.ConnectAsync();

            await Task.Delay(1000);

            await client2.EmitAsync("create room", room);

            //需要添加 EmitAsync("event",roomName,data);

            await Task.Delay(1000);

            Assert.AreEqual(client1Msg, client2Msg);
        }
Exemple #27
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>());
        }
Exemple #28
0
        public async Task ReceivedEventTest()
        {
            var    client = new SocketIO("http://localhost:3000");
            string en1    = string.Empty;
            string text1  = string.Empty;
            string text2  = string.Empty;
            string guid   = Guid.NewGuid().ToString();

            client.OnReceivedEvent += (eventName, args) =>
            {
                en1   = eventName;
                text1 = args.Text;
            };
            client.On("test", args =>
            {
                text2 = args.Text;
            });
            await client.ConnectAsync();

            await Task.Delay(1000);

            await client.EmitAsync("test", guid);

            await Task.Delay(1000);

            Assert.AreEqual("test", en1);
            Assert.AreEqual($"\"{guid} - server\"", text1);
            Assert.AreEqual(text1, text2);
            await client.ConnectAsync();
        }
Exemple #29
0
        public async Task ClientBinaryCallbackTest()
        {
            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) =>
            {
                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));
        }
Exemple #30
0
        public async Task EventChangeTest()
        {
            string         resVal1 = null;
            ChangeResponse resVal2 = null;
            var            client  = new SocketIO(Uri, new SocketIOOptions
            {
                Query = new Dictionary <string, string>
                {
                    { "token", "io" }
                }
            });

            client.OnConnected += async(sender, e) =>
            {
                await client.EmitAsync("change", new
                {
                    code    = 200,
                    message = "val1"
                }, "val2");
            };
            client.On("change", response =>
            {
                resVal1 = response.GetValue <string>();
                resVal2 = response.GetValue <ChangeResponse>(1);
            });
            await client.ConnectAsync();

            await Task.Delay(200);

            await client.DisconnectAsync();

            Assert.AreEqual("val2", resVal1);
            Assert.AreEqual(200, resVal2.Code);
            Assert.AreEqual("val1", resVal2.Message);
        }
Exemple #31
0
 private void OnReadyPlay(SocketIO.SocketIOEvent evt )
 {
     Debug.Log("READY TO PLAY");
     //		float py = HitFactor(transform.position, col.transform.position, col.collider.bounds.size.y);
     //		Vector2 direction = new  Vector2(1,py).normalized;
     //		GetComponent<Rigidbody2D>().velocity = direction*ballSpeed;
     StartCom();
 }
Exemple #32
0
    public static SocketIO getInstance()
    {
        if (instance == null) {
            instance = new SocketIO();
            instance.InitSocket();
        }

        return instance;
    }
        public CavetubeClient()
        {
            this.Connector = new SocketIO();

            this.Connector.OnOpen += e =>
            {
                this.RaiseOnOpen(new CavetubeClientOnOpenEventArgs());
            };

            this.Connector.OnClose += e =>
            {
                this.RaiseOnClose(new CavetubeClientOnCloseEventArgs());
            };

            this.Connector.OnError += e =>
            {
                this.RaiseOnError(new CavetubeClientOnErrorEventArgs(e.Error));
            };

            //別スレッドからだとRaisePropertyChangedが動かない。
            //WPF4で改善予定
            /*this.Connector.OnMessage += e =>*/
            Observable.FromEvent<SocketIOOnMessageCallback, SocketIOOnMessageEventArgs>(a => this.Connector.OnMessage += a, a => this.Connector.OnMessage -= a)
                .ObserveOnDispatcher()
                .Subscribe(e =>
            {
                dynamic json = DynamicJson.Parse(e.ReceivedMessage);

                if (json.mode == "post")
                {
                    var comment = new CavetubeComment()
                    {
                        Number = (int)json.comment_num,
                        Text = json.message
                    };

                    var time = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                        .AddMilliseconds(json.time)
                        .AddTicks(TimeZoneInfo.Local.BaseUtcOffset.Ticks);

                    comment.PostDate = time;

                    if (json.auth)
                    {
                        comment.Name = json.name;
                    }
                    this.RaiseOnMessage(new CavetubeClientOnMessageEventArgs(comment));
                }
            });
        }
Exemple #34
0
    private void OnGetShoot( SocketIO.SocketIOEvent evt )
    {
        Debug.Log("Recieve Rocket "+evt.data.GetField("rocket").ToString());
        Debug.Log("Recieve Float "+evt.data.GetField("float").ToString());
        if( Converter.JsonToString(evt.data.GetField("rocket").ToString()) == "RocketLeft" ){

            Vector2 direction = new  Vector2(1,Converter.JsonToFloat(evt.data.GetField("float").ToString())).normalized;
            GetComponent<Rigidbody2D>().velocity = direction*ballSpeed;
        }

        if(Converter.JsonToString(evt.data.GetField("rocket").ToString()) == "RocketRight" ){
            Vector2 direction = new  Vector2(-1,Converter.JsonToFloat(evt.data.GetField("float").ToString())).normalized;
            GetComponent<Rigidbody2D>().velocity = direction*ballSpeed;
        }
    }
        public CavetubeClient()
        {
            this.Connector = new SocketIO();

            this.Connector.OnOpen += e =>
            {
                this.RaiseOnOpen(new CavetubeClientOnOpenEventArgs());
                this.Connector.Send(SocketIOMessageType.Message, @"{ ""mode"" : ""join"", ""room"" : ""/"" }");
            };

            this.Connector.OnClose += e =>
            {
                this.RaiseOnClose(new CavetubeClientOnCloseEventArgs());
            };

            this.Connector.OnError += e =>
            {
                this.RaiseOnError(new CavetubeClientOnErrorEventArgs(e.Error));
            };

            //別スレッドからだとRaisePropertyChangedが動かない。
            /*this.Connector.OnMessage += e =>*/
            Observable.FromEvent<SocketIOOnMessageCallback, SocketIOOnMessageEventArgs>(a => this.Connector.OnMessage += a, a => this.Connector.OnMessage -= a)
                .ObserveOnDispatcher()
                .Subscribe(e =>
            {
                dynamic json = DynamicJson.Parse(e.ReceivedMessage);

                Debug.WriteLine(e.ReceivedMessage);
            });

            this.Open();
        }
Exemple #36
0
 public void AddSocketIO(SocketIO.SocketIO socketIO, string Namespace = "socket.io")
 {
     AddDynamic("^/" + Namespace + "/1/$", socketIO.Handshake);
     AddWebSocket("^/" + Namespace + "/1/websocket/(.*)$", socketIO.GetWebSocket);
     AddWebSocket("^/" + Namespace + "/1/flashsocket/(.*)$", socketIO.GetFlashSocket);
     AddDynamic("^/" + Namespace + "/1/xhr-polling/(.*)$", socketIO.XhrPolling);
     AddDynamic("^/" + Namespace + "/1/jsonp-polling/(.*)$", socketIO.JsonpPolling);
 }