Ejemplo n.º 1
0
        public static IDisposable ClientGroupsSyncWithServerGroupsOnReconnectLongPolling()
        {
            var host = new MemoryHost();

            host.Configuration.KeepAlive = null;
            host.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(5);
            host.Configuration.HeartbeatInterval = TimeSpan.FromSeconds(2);
            host.MapConnection<MyRejoinGroupConnection>("/groups");

            var connection = new Client.Connection("http://foo/groups");
            var inGroupOnReconnect = new List<bool>();
            var wh = new ManualResetEventSlim();

            connection.Received += message =>
            {
                Console.WriteLine(message);
                wh.Set();
            };

            connection.Reconnected += () =>
            {
                var inGroup = connection.Groups.Contains(typeof(MyRejoinGroupConnection).FullName + ".test");

                if (!inGroup)
                {
                    Debugger.Break();
                }

                inGroupOnReconnect.Add(inGroup);

                connection.Send(new { type = 3, group = "test", message = "Reconnected" }).Wait();
            };

            connection.Start(new Client.Transports.LongPollingTransport(host)).Wait();

            // Join the group
            connection.Send(new { type = 1, group = "test" }).Wait();

            Thread.Sleep(TimeSpan.FromSeconds(10));

            if (!wh.Wait(TimeSpan.FromSeconds(10)))
            {
                Debugger.Break();
            }

            Console.WriteLine(inGroupOnReconnect.Count > 0);
            Console.WriteLine(String.Join(", ", inGroupOnReconnect.Select(b => b.ToString())));

            connection.Stop();

            return host;
        }
Ejemplo n.º 2
0
            public void SendRaisesOnReceivedFromAllEvents()
            {
                var host = new MemoryHost();

                host.MapConnection <MySendingConnection>("/multisend");

                var connection = new Client.Connection("http://foo/multisend");
                var results    = new List <string>();

                connection.Received += data =>
                {
                    results.Add(data);
                };

                connection.Start(host).Wait();
                connection.Send("").Wait();

                Thread.Sleep(TimeSpan.FromSeconds(5));

                connection.Stop();

                Debug.WriteLine(String.Join(", ", results));

                Assert.Equal(4, results.Count);
                Assert.Equal("OnConnectedAsync1", results[0]);
                Assert.Equal("OnConnectedAsync2", results[1]);
                Assert.Equal("OnReceivedAsync1", results[2]);
                Assert.Equal("OnReceivedAsync2", results[3]);
            }
Ejemplo n.º 3
0
            public void SendToAllButCaller()
            {
                var host = new MemoryHost();

                host.MapConnection <FilteredConnection>("/filter");
                var connection1 = new Client.Connection("http://foo/filter");
                var connection2 = new Client.Connection("http://foo/filter");

                var wh1 = new ManualResetEventSlim(initialState: false);
                var wh2 = new ManualResetEventSlim(initialState: false);

                connection1.Received += data => wh1.Set();
                connection2.Received += data => wh2.Set();

                connection1.Start(host).Wait();
                connection2.Start(host).Wait();

                connection1.Send("test").Wait();

                Assert.False(wh1.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)));
                Assert.True(wh2.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)));

                connection1.Stop();
                connection2.Stop();
            }
Ejemplo n.º 4
0
        public async Task ConnectionIdsCantBeUsedAsGroups()
        {
            using (var host = new MemoryHost())
            {
                IProtectedData protectedData = null;

                host.Configure(app =>
                {
                    var config = new ConnectionConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    app.MapSignalR <MyConnection>("/echo", config);

                    protectedData = config.Resolver.Resolve <IProtectedData>();
                });

                var connection = new Client.Connection("http://memoryhost/echo");

                using (connection)
                {
                    var connectionTcs = new TaskCompletionSource <string>();
                    var spyTcs        = new TaskCompletionSource <string>();

                    connection.Received += data =>
                    {
                        connectionTcs.SetResult(data.Trim());
                    };

                    await connection.Start(host).OrTimeout();

                    EventSourceStreamReader reader = null;

                    await Task.Run(async() =>
                    {
                        var url      = GetUrl(protectedData, connection);
                        var response = await host.Get(url, r => { }, isLongRunning: true);
                        reader       = new EventSourceStreamReader(connection, response.GetStream());

                        reader.Message = sseEvent =>
                        {
                            if (sseEvent.EventType == EventType.Data &&
                                sseEvent.Data != "initialized" &&
                                sseEvent.Data != "{}")
                            {
                                spyTcs.TrySetResult(sseEvent.Data);
                            }
                        };

                        reader.Start();
                    });

                    await connection.Send("STUFFF").OrTimeout();

                    Assert.Equal("STUFFF", await connectionTcs.Task.OrTimeout());
                }
            }
        }
Ejemplo n.º 5
0
            public void ClientGroupsSyncWithServerGroupsOnReconnect(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: null,
                                    connectonTimeOut: 5,
                                    hearbeatInterval: 2);

                    var connection = new Client.Connection(host.Url + "/rejoin-groups");
                    var inGroupOnReconnect = new List<bool>();
                    var wh = new ManualResetEventSlim();

                    connection.Received += message =>
                    {
                        Assert.Equal("Reconnected", message);
                        wh.Set();
                    };

                    connection.Reconnected += () =>
                    {
                        inGroupOnReconnect.Add(connection.Groups.Contains(typeof(MyRejoinGroupsConnection).FullName + ".test"));

                        connection.Send(new { type = 3, group = "test", message = "Reconnected" }).Wait();
                    };

                    connection.Start(host.Transport).Wait();

                    // Join the group
                    connection.Send(new { type = 1, group = "test" }).Wait();

                    // Force reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(10));

                    Assert.True(wh.Wait(TimeSpan.FromSeconds(5)), "Client didn't receive message sent to test group.");
                    Assert.True(inGroupOnReconnect.Count > 0);
                    Assert.True(inGroupOnReconnect.All(b => b));

                    connection.Stop();
                }
            }
Ejemplo n.º 6
0
            public void GroupsRejoinedWhenOnRejoiningGroupsOverridden()
            {
                using (var host = new MemoryHost())
                {
                    host.Configuration.KeepAlive         = null;
                    host.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(2);
                    host.Configuration.HeartBeatInterval = TimeSpan.FromSeconds(2);
                    host.MapConnection <MyRejoinGroupConnection>("/groups");

                    var connection = new Client.Connection("http://foo/groups");
                    var list       = new List <string>();
                    connection.Received += data =>
                    {
                        list.Add(data);
                    };

                    connection.Start(host).Wait();

                    // Join the group
                    connection.Send(new { type = 1, group = "test" }).Wait();

                    // Sent a message
                    connection.Send(new { type = 3, group = "test", message = "hello to group test" }).Wait();

                    // Force Reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    // Send a message
                    connection.Send(new { type = 3, group = "test", message = "goodbye to group test" }).Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(2, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                    Assert.Equal("goodbye to group test", list[1]);
                }
            }
Ejemplo n.º 7
0
        private static void Main()
        {
            const string url = "http://*****:*****@ {1}", connection.Url, DateTime.Now);
                                connection.Send("Hello Server");
                                Thread.Sleep(2000);
                            }
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception);
                        }
                    }
                });

            Console.ReadLine();
        }
Ejemplo n.º 8
0
        private static void BroadcastFive(MemoryHost host)
        {
            var connection = new Client.Connection("http://samples/Raw-connection");

            connection.Error += e =>
            {
                Console.Error.WriteLine("========ERROR==========");
                Console.Error.WriteLine(e.GetBaseException().ToString());
                Console.Error.WriteLine("=======================");
            };

            connection.Start(new Client.Transports.ServerSentEventsTransport(host)).Wait();

            try
            {
                for (int i = 0; i < 5; i++)
                {
                    var payload = new
                    {
                        type  = MessageType.Broadcast,
                        value = "message " + i.ToString()
                    };

                    connection.Send(payload).Wait();
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("========ERROR==========");
                Console.Error.WriteLine(ex.GetBaseException().ToString());
                Console.Error.WriteLine("=======================");
            }
            finally
            {
                connection.Stop();
            }
        }
Ejemplo n.º 9
0
        public static void SendWithTimeout(this Client.Connection connection, string data, TimeSpan timeout)
        {
            var task = connection.Send(data);

            Assert.True(task.Wait(timeout), "Failed to get response from send");
        }
Ejemplo n.º 10
0
            public void SendToAllButCaller()
            {
                var host = new MemoryHost();
                host.MapConnection<FilteredConnection>("/filter");
                var connection1 = new Client.Connection("http://foo/filter");
                var connection2 = new Client.Connection("http://foo/filter");

                var wh1 = new ManualResetEventSlim(initialState: false);
                var wh2 = new ManualResetEventSlim(initialState: false);

                connection1.Received += data => wh1.Set();
                connection2.Received += data => wh2.Set();

                connection1.Start(host).Wait();
                connection2.Start(host).Wait();

                connection1.Send("test").Wait();

                Assert.False(wh1.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)));
                Assert.True(wh2.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)));

                connection1.Stop();
                connection2.Stop();
            }
Ejemplo n.º 11
0
        private static void BroadcastFive(MemoryHost host)
        {
            var connection = new Client.Connection("http://samples/Raw-connection");

            connection.Error += e =>
            {
                Console.Error.WriteLine("========ERROR==========");
                Console.Error.WriteLine(e.GetBaseException().ToString());
                Console.Error.WriteLine("=======================");
            };

            connection.Start(new Client.Transports.ServerSentEventsTransport(host)).Wait();

            try
            {
                for (int i = 0; i < 5; i++)
                {
                    var payload = new
                    {
                        type = MessageType.Broadcast,
                        value = "message " + i.ToString()
                    };

                    connection.Send(payload).Wait();
                }

            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("========ERROR==========");
                Console.Error.WriteLine(ex.GetBaseException().ToString());
                Console.Error.WriteLine("=======================");
            }
            finally
            {
                connection.Stop();
            }
        }
Ejemplo n.º 12
0
        public static IDisposable ClientGroupsSyncWithServerGroupsOnReconnectLongPolling()
        {
            var host = new MemoryHost();

            host.Configure(app =>
            {
                var config = new ConnectionConfiguration()
                {
                    Resolver = new DefaultDependencyResolver()
                };

                app.MapConnection<MyRejoinGroupConnection>("/groups", config);

                var configuration = config.Resolver.Resolve<IConfigurationManager>();
                configuration.KeepAlive = null;
                configuration.ConnectionTimeout = TimeSpan.FromSeconds(1);
            });

            var connection = new Client.Connection("http://foo/groups");
            var inGroupOnReconnect = new List<bool>();
            var wh = new ManualResetEventSlim();

            connection.Received += message =>
            {
                Console.WriteLine(message);
                wh.Set();
            };

            connection.Reconnected += () =>
            {
                connection.Send(new { type = 3, group = "test", message = "Reconnected" }).Wait();
            };

            connection.Start(new Client.Transports.LongPollingTransport(host)).Wait();

            // Join the group
            connection.Send(new { type = 1, group = "test" }).Wait();

            Thread.Sleep(TimeSpan.FromSeconds(10));

            if (!wh.Wait(TimeSpan.FromSeconds(10)))
            {
                Debugger.Break();
            }

            Console.WriteLine(inGroupOnReconnect.Count > 0);
            Console.WriteLine(String.Join(", ", inGroupOnReconnect.Select(b => b.ToString())));

            connection.Stop();

            return host;
        }
Ejemplo n.º 13
0
            public void GroupsRejoinedWhenOnRejoiningGroupsOverridden(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: null,
                                    connectonTimeOut: 2,
                                    hearbeatInterval: 2);

                    var connection = new Client.Connection(host.Url + "/rejoin-groups");

                    var list = new List<string>();
                    connection.Received += data =>
                    {
                        list.Add(data);
                    };

                    connection.Start(host.Transport).Wait();

                    // Join the group
                    connection.Send(new { type = 1, group = "test" }).Wait();

                    // Sent a message
                    connection.Send(new { type = 3, group = "test", message = "hello to group test" }).Wait();

                    // Force Reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    // Send a message
                    connection.Send(new { type = 3, group = "test", message = "goodbye to group test" }).Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(2, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                    Assert.Equal("goodbye to group test", list[1]);
                }
            }
Ejemplo n.º 14
0
            public void GroupsRejoinedWhenOnRejoiningGroupsOverridden()
            {
                var host = new MemoryHost();
                host.Configuration.KeepAlive = null;
                host.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(2);
                host.Configuration.HeartBeatInterval = TimeSpan.FromSeconds(2);
                host.MapConnection<MyRejoinGroupConnection>("/groups");

                var connection = new Client.Connection("http://foo/groups");
                var list = new List<string>();
                connection.Received += data =>
                {
                    list.Add(data);
                };

                connection.Start(host).Wait();

                // Join the group
                connection.Send(new { type = 1, group = "test" }).Wait();

                // Sent a message
                connection.Send(new { type = 3, group = "test", message = "hello to group test" }).Wait();

                // Force Reconnect
                Thread.Sleep(TimeSpan.FromSeconds(5));

                // Send a message
                connection.Send(new { type = 3, group = "test", message = "goodbye to group test" }).Wait();

                Thread.Sleep(TimeSpan.FromSeconds(5));

                connection.Stop();

                Assert.Equal(2, list.Count);
                Assert.Equal("hello to group test", list[0]);
                Assert.Equal("goodbye to group test", list[1]);
            }
Ejemplo n.º 15
0
            public void SendToAllButCaller(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize();

                    var connection1 = new Client.Connection(host.Url + "/filter");
                    var connection2 = new Client.Connection(host.Url + "/filter");

                    var wh1 = new ManualResetEventSlim(initialState: false);
                    var wh2 = new ManualResetEventSlim(initialState: false);

                    connection1.Received += data => wh1.Set();
                    connection2.Received += data => wh2.Set();

                    connection1.Start(host.Transport).Wait();
                    connection2.Start(host.Transport).Wait();

                    connection1.Send("test").Wait();

                    Assert.False(wh1.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)));
                    Assert.True(wh2.WaitHandle.WaitOne(TimeSpan.FromSeconds(5)));

                    connection1.Stop();
                    connection2.Stop();
                }
            }
Ejemplo n.º 16
0
            public void SendRaisesOnReceivedFromAllEvents(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize();

                    var connection = new Client.Connection(host.Url + "/multisend");
                    var results = new List<string>();
                    connection.Received += data =>
                    {
                        results.Add(data);
                    };

                    connection.Start(host.Transport).Wait();
                    connection.Send("").Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Debug.WriteLine(String.Join(", ", results));

                    Assert.Equal(4, results.Count);
                    Assert.Equal("OnConnectedAsync1", results[0]);
                    Assert.Equal("OnConnectedAsync2", results[1]);
                    Assert.Equal("OnReceivedAsync1", results[2]);
                    Assert.Equal("OnReceivedAsync2", results[3]);
                }
            }
Ejemplo n.º 17
0
            public void SendCanBeCalledAfterStateChangedEvent(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize();

                    var connection = new Client.Connection(host.Url + "/multisend");
                    var results = new List<string>();
                    connection.Received += data =>
                    {
                        results.Add(data);
                    };

                    connection.StateChanged += stateChange =>
                    {
                        if (stateChange.NewState == Client.ConnectionState.Connected)
                        {
                            connection.Send("").Wait();
                        }
                    };

                    connection.Start(host.Transport).Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Debug.WriteLine(String.Join(", ", results));

                    Assert.Equal(4, results.Count);
                }
            }
Ejemplo n.º 18
0
            public void GroupsReceiveMessages()
            {
                var host = new MemoryHost();
                host.MapConnection<MyGroupConnection>("/groups");

                var connection = new Client.Connection("http://foo/groups");
                var list = new List<string>();
                connection.Received += data =>
                {
                    list.Add(data);
                };

                connection.Start(host).Wait();

                // Join the group
                connection.Send(new { type = 1, group = "test" }).Wait();

                // Sent a message
                connection.Send(new { type = 3, group = "test", message = "hello to group test" }).Wait();

                // Leave the group
                connection.Send(new { type = 2, group = "test" }).Wait();

                // Send a message
                connection.Send(new { type = 3, group = "test", message = "goodbye to group test" }).Wait();

                Thread.Sleep(TimeSpan.FromSeconds(5));

                connection.Stop();

                Assert.Equal(1, list.Count);
                Assert.Equal("hello to group test", list[0]);
            }
Ejemplo n.º 19
0
            public void GroupsReceiveMessages(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize();

                    var connection = new Client.Connection(host.Url + "/groups");
                    var list = new List<string>();
                    connection.Received += data =>
                    {
                        list.Add(data);
                    };

                    connection.Start(host.Transport).Wait();

                    // Join the group
                    connection.Send(new { type = 1, group = "test" }).Wait();

                    // Sent a message
                    connection.Send(new { type = 3, group = "test", message = "hello to group test" }).Wait();

                    // Leave the group
                    connection.Send(new { type = 2, group = "test" }).Wait();

                    // Send a message
                    connection.Send(new { type = 3, group = "test", message = "goodbye to group test" }).Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Assert.Equal(1, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                }
            }
Ejemplo n.º 20
0
        public async Task GroupsTokenIsPerConnectionId()
        {
            using (var host = new MemoryHost())
            {
                IProtectedData protectedData = null;

                host.Configure(app =>
                {
                    var config = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    app.MapSignalR <MyGroupConnection>("/echo", config);

                    protectedData = config.Resolver.Resolve <IProtectedData>();
                });

                var connection = new Client.Connection("http://memoryhost/echo");

                using (connection)
                {
                    var inGroup = new AsyncManualResetEvent();

                    connection.Received += data =>
                    {
                        if (data == "group")
                        {
                            inGroup.Set();
                        }
                    };

                    await connection.Start(host);

                    await inGroup.WaitAsync(TimeSpan.FromSeconds(10));

                    Assert.NotNull(connection.GroupsToken);

                    var spyWh            = new AsyncManualResetEvent();
                    var hackerConnection = new Client.Connection(connection.Url)
                    {
                        ConnectionId = "hacker"
                    };

                    var url      = GetUrl(protectedData, connection, connection.GroupsToken);
                    var response = await host.Get(url, r => { }, isLongRunning : true);

                    var reader = new EventSourceStreamReader(hackerConnection, response.GetStream());

                    reader.Message = sseEvent =>
                    {
                        if (sseEvent.EventType == EventType.Data &&
                            sseEvent.Data != "initialized" &&
                            sseEvent.Data != "{}")
                        {
                            spyWh.Set();
                        }
                    };

                    reader.Start();
                    await connection.Send("random");

                    Assert.False(await spyWh.WaitAsync(TimeSpan.FromSeconds(5)));
                }
            }
        }
Ejemplo n.º 21
0
        public async Task GroupsTokenIsPerConnectionId()
        {
            using (var host = new MemoryHost())
            {
                IProtectedData protectedData = null;

                host.Configure(app =>
                {
                    var config = new HubConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    app.MapSignalR<MyGroupConnection>("/echo", config);

                    protectedData = config.Resolver.Resolve<IProtectedData>();
                });

                var connection = new Client.Connection("http://memoryhost/echo");

                using (connection)
                {
                    var inGroup = new AsyncManualResetEvent();

                    connection.Received += data =>
                    {
                        if (data == "group")
                        {
                            inGroup.Set();
                        }
                    };

                    await connection.Start(host);

                    await inGroup.WaitAsync(TimeSpan.FromSeconds(10));

                    Assert.NotNull(connection.GroupsToken);

                    var spyWh = new AsyncManualResetEvent();
                    var hackerConnection = new Client.Connection(connection.Url)
                    {
                        ConnectionId = "hacker"
                    };

                    var url = GetUrl(protectedData, connection, connection.GroupsToken);
                    var response = await host.Get(url, r => { }, isLongRunning: true);
                    var reader = new EventSourceStreamReader(hackerConnection, response.GetStream());

                    reader.Message = sseEvent =>
                    {
                        if (sseEvent.EventType == EventType.Data &&
                            sseEvent.Data != "initialized" &&
                            sseEvent.Data != "{}")
                        {
                            spyWh.Set();
                        }
                    };

                    reader.Start();
                    await connection.Send("random");

                    Assert.False(await spyWh.WaitAsync(TimeSpan.FromSeconds(5)));
                }
            }
        }
Ejemplo n.º 22
0
            public void SendRaisesOnReceivedFromAllEvents()
            {
                var host = new MemoryHost();
                host.MapConnection<MySendingConnection>("/multisend");

                var connection = new Client.Connection("http://foo/multisend");
                var results = new List<string>();
                connection.Received += data =>
                {
                    results.Add(data);
                };

                connection.Start(host).Wait();
                connection.Send("").Wait();

                Thread.Sleep(TimeSpan.FromSeconds(10));

                Debug.WriteLine(String.Join(", ", results));

                Assert.Equal(4, results.Count);
                Assert.Equal("OnConnectedAsync1", results[0]);
                Assert.Equal("OnConnectedAsync2", results[1]);
                Assert.Equal("OnReceivedAsync1", results[2]);
                Assert.Equal("OnReceivedAsync2", results[3]);
            }
Ejemplo n.º 23
0
            public void SendCanBeCalledAfterStateChangedEvent()
            {
                using (var host = new MemoryHost())
                {
                    host.MapConnection<MySendingConnection>("/multisend");

                    var connection = new Client.Connection("http://foo/multisend");
                    var results = new List<string>();
                    connection.Received += data =>
                    {
                        results.Add(data);
                    };

                    connection.StateChanged += stateChange =>
                    {
                        if (stateChange.NewState == Client.ConnectionState.Connected)
                        {
                            connection.Send("").Wait();
                        }
                    };

                    connection.Start(host).Wait();

                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    connection.Stop();

                    Debug.WriteLine(String.Join(", ", results));

                    Assert.Equal(4, results.Count);
                }
            }