コード例 #1
0
        public MainWindow()
        {
            socket.ConnectAsync(new Uri($"{Server}:{Port}"));
            //System.Net.WebRequest.DefaultWebProxy = null;
            InitializeComponent();

            //socket.On("connect", (fn) =>
            //{
            //    Console.WriteLine("\r\nConnected event...\r\n");

            //});

            // register for 'update' events - message is a json 'Part' object
            socket.On(ResponseEventName, (data) =>
            {
                Console.WriteLine("recv [socket].[update] event");

                // cast message as Part - use type cast helper
                //this.lblResult.Content = data.MessageText;

                this.Dispatcher.Invoke(() =>
                {
                    this.lblResult.Content = data;
                });
            });

            // make the socket.io connection
//            socket.Connect();
        }
コード例 #2
0
        public IObservable <Dictionary <string, object> > Connect(
            IObservable <string> input,
            ICollection <IMessageUnpacker> unpackers)
        {
            return(Observable.Defer(() => Observable.Create <Dictionary <string, object> >(async(sink, token) =>
            {
                SocketIoClient socket = new SocketIoClient();

                Uri connectionUri = null;
                try
                {
                    connectionUri = new Uri("https://streamer.cryptocompare.com");
                    await socket.ConnectAsync(connectionUri);
                    _logger.LogInformation("[EXTERNAL-SERVICE] Connecting to CryptoCompare.com ...");
                }
                catch (UriFormatException e)
                {
                    sink.OnError(e);
                    return;
                }

                Func <Task> closeSocket = async() => {
                    await socket.DisconnectAsync();
                    _logger.LogInformation("[EXTERNAL-SERVICE] Connection to CryptoCompare.com closed");
                };

                socket.Connected += (sender, args) =>
                {
                    input.Subscribe(v =>
                    {
                        string[] subscription = { v };
                        Dictionary <string, object> subs = new Dictionary <string, object>();
                        subs.Add("subs", subscription);
                        socket.Emit("SubAdd", subs);
                    },
                                    onError: e => sink.OnError(e));
                };

                socket.On("m", async args =>
                {
                    string message = args;
                    string messageType = message.Substring(0, message.IndexOf("~"));
                    foreach (IMessageUnpacker unpacker in unpackers)
                    {
                        if (unpacker.Supports(messageType))
                        {
                            try
                            {
                                sink.OnNext(unpacker.Unpack(message));
                            }
                            catch (Exception e)
                            {
                                sink.OnError(e);
                                await closeSocket.Invoke();
                            }
                            break;
                        }
                    }
                });

                socket.ErrorReceived += (sender, args) => sink.OnError(new Exception(args.Value));
                socket.Disconnected += (sender, args) => sink.OnCompleted();

                token.Register(async() => await closeSocket());
                await socket.ConnectAsync(connectionUri);
            })));
        }
        public async Task NoAcksOrHandlerNotifications()
        {
            // Arrange
            var serializer = new NewtonSoftJsonSerializer();
            var logger     = new NullLogger <SocketIoClient>();
            var opts       = new SocketIoClientOptions(
                serializer,
                logger,
                Encoding.UTF8
                );
            var client = new SocketIoClient(opts);

            client.Events.OnConnect.Subscribe(
                args => Log($"[1] Connected: {args}"));
            client.Events.OnPacket.Subscribe(packet =>
            {
                Log($"[1] Received packet: {packet}");
            });
            string clientId1 = null;

            client.Events.OnHandshake.Subscribe(res =>
            {
                clientId1 = res.Sid;
            });
            // Act
            await client.OpenAsync(new Uri("http://localhost:3300"));

            var data1 = new Payload()
            {
                Id   = 42,
                Name = "Douglas Adams"
            };
            var data2 = new Payload()
            {
                Id   = 86,
                Name = "Carl Sagan"
            };

            while (clientId1 is null)
            {
                Thread.Sleep(50);
            }

            client.On("/consume")
            .Subscribe(message =>
            {
                Log($"Received notification: {message.EventName}, data: {message.Data}");
            });

            Log($"- subscribe to 'test' topic {clientId1} -");
            client.Emit("/subscribe", new SubscribeRequest(
                            clientId1,
                            "test",
                            0,
                            10,
                            0
                            )
                        ).Subscribe(ack =>
            {
                Log($"subscribe ack: {ack}");
            });


            Log("- about to publish - ");
            client.Emit("/publish", new PublishRequest
            {
                Topic   = "test",
                Channel = 1,
                Message = JsonConvert.SerializeObject(data1)
            }
                        ).Subscribe(ack =>
            {
                Log($"publish ack: {JsonConvert.SerializeObject(ack)}");
            });

            client.Emit("/publish", new PublishRequest
            {
                Topic   = "test",
                Channel = 1,
                Message = JsonConvert.SerializeObject(data1)
            }
                        ).Subscribe(ack =>
            {
                Log($"publish ack: {JsonConvert.SerializeObject(ack)}");
            });

            // Assert
            Log("- waiting for 2s just in case -");
            await Task.Delay(2000);

            Log("- test ends -");
        }
コード例 #4
0
        public WebSocket(string url_)
        {
            url = url_;
            GetPayload();
            if (title == "Toonation")
            {
                webSocket            = new WebSocketSharp.WebSocket("wss://toon.at:8071/" + payload);
                webSocket.OnMessage += Ws_OnMessage;
                webSocket.OnClose   += Ws_OnClose;
                webSocket.Connect();
            }
            else if (title == "Twip AlertBox")
            {
                string ioUrl = $"https://io.mytwip.net?alertbox_key={key}&version={version}&token={encodeURIComponent(token)}";

                var client = new SocketIoClient();
                client.Connected              += (sender, args) => Debug.WriteLine($"Connected: {args.Namespace}");
                client.Disconnected           += (sender, args) => Debug.WriteLine($"Disconnected. Reason: {args.Reason}, Status: {args.Status:G}");
                client.EventReceived          += (sender, args) => Debug.WriteLine($"EventReceived: Namespace: {args.Namespace}, Value: {args.Value}, IsHandled: {args.IsHandled}");
                client.HandledEventReceived   += (sender, args) => Debug.WriteLine($"HandledEventReceived: Namespace: {args.Namespace}, Value: {args.Value}");
                client.UnhandledEventReceived += (sender, args) => Debug.WriteLine($"UnhandledEventReceived: Namespace: {args.Namespace}, Value: {args.Value}");
                client.ErrorReceived          += (sender, args) => Debug.WriteLine($"ErrorReceived: Namespace: {args.Namespace}, Value: {args.Value}");
                client.ExceptionOccurred      += (sender, args) => Debug.WriteLine($"ExceptionOccurred: {args.Value}");
                client.On("new donate", message =>
                {
                    eCurrentMessageKind = EMessageKind.donate;
                    Console.WriteLine(message);
                    var obj = JsonConvert.DeserializeObject <TwipObject>(message);
                    if (obj.effect != null)
                    {
                        if (obj.slotmachine_data != null)
                        {
                            eCurrentMessageKind = EMessageKind.roulette;
                        }
                        OnTwipObject?.Invoke(obj);
                    }
                });
                client.On("new cheer", message =>
                {
                    eCurrentMessageKind = EMessageKind.cheer;
                    Console.WriteLine(message);
                    var obj = JsonConvert.DeserializeObject <TwipObject>(message);
                    if (obj.effect != null)
                    {
                        OnTwipObject?.Invoke(obj);
                    }
                });
                client.On("new follow", message =>
                {
                    eCurrentMessageKind = EMessageKind.follow;
                    Console.WriteLine(message);
                    var obj = JsonConvert.DeserializeObject <TwipObject>(message);
                    if (obj.effect != null)
                    {
                        OnTwipObject?.Invoke(obj);
                    }
                });
                client.On("new sub", message =>
                {
                    eCurrentMessageKind = EMessageKind.sub;
                    Console.WriteLine(message);
                    var obj = JsonConvert.DeserializeObject <TwipObject>(message);
                    if (obj.effect != null)
                    {
                        OnTwipObject?.Invoke(obj);
                    }
                });
                client.On("new hosting", message =>
                {
                    eCurrentMessageKind = EMessageKind.hosting;

                    Console.WriteLine(message);
                    var obj = JsonConvert.DeserializeObject <TwipObject>(message);
                    if (obj.effect != null)
                    {
                        OnTwipObject?.Invoke(obj);
                    }
                });
                client.On("new redemption", message =>
                {
                    eCurrentMessageKind = EMessageKind.redemption;
                    Console.WriteLine(message);
                    var obj = JsonConvert.DeserializeObject <TwipObject>(message);
                    if (obj.effect != null)
                    {
                        OnTwipObject?.Invoke(obj);
                    }
                });
                client.ConnectAsync(new Uri(ioUrl)).Wait();
            }
            jsonSettings = new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore
            };
        }