• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Client.Connection类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Client.Connection的典型用法代码示例。如果您正苦于以下问题:C# Client.Connection类的具体用法?C# Client.Connection怎么用?C# Client.Connection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Client.Connection类属于命名空间,在下文中一共展示了Client.Connection类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: TestClientConnectionTearDown

 public void TestClientConnectionTearDown()
 {
     mocks = null;
     mockSocket = null;
     mockClient = null;
     connection = null;
 }
开发者ID:Carterj3,项目名称:Caesura,代码行数:7,代码来源:TestClientConnection.cs


示例2: TestClientRequestFileRealConnectionSuccess

        public void TestClientRequestFileRealConnectionSuccess()
        {
            Client.Connection temp = new Client.Connection(client);
            client.connection = temp;
            temp.sock = mockSocket;

            using (mocks.Record())
            {
                mockSocket.send(iSocket.aSocket.stringToBytes("RequestFile generic.txt"));

                // File Name
                mockSocket.receive(iSocket.constants.MAXPACKETSIZE);
                LastCall.Return(iSocket.aSocket.stringToBytes("generic.txt", iSocket.constants.MAXPACKETSIZE)).Repeat.Once();
                // Number of transfers (1)
                mockSocket.receive(iSocket.constants.MAXPACKETSIZE);
                LastCall.Return(iSocket.aSocket.stringToBytes("1", iSocket.constants.MAXPACKETSIZE)).Repeat.Once();
                // Length of a transfer
                mockSocket.receive(iSocket.constants.MAXPACKETSIZE);
                LastCall.Return(iSocket.aSocket.stringToBytes("18", iSocket.constants.MAXPACKETSIZE)).Repeat.Once();
                // Transfer
                mockSocket.receive(iSocket.constants.MAXPACKETSIZE);
                LastCall.Return(iSocket.aSocket.stringToBytes("This here is a text file", iSocket.constants.MAXPACKETSIZE)).Repeat.Once();
            }

            //Assert.IsTrue(client.requestFile("generic.txt"));
            mocks.VerifyAll();
        }
开发者ID:Carterj3,项目名称:Caesura,代码行数:27,代码来源:TestClient.cs


示例3: GroupsReceiveMessages

            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.SendWithTimeout(new { type = 1, group = "test" });

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

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

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

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

                    connection.Stop();

                    Assert.Equal(1, list.Count);
                    Assert.Equal("hello to group test", list[0]);
                }
            }
开发者ID:elylucas,项目名称:SignalR,代码行数:35,代码来源:PersistentConnectionFacts.cs


示例4: ThrownWebExceptionShouldBeUnwrapped

            public void ThrownWebExceptionShouldBeUnwrapped(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize();

                    var connection = new Client.Connection(host.Url + "/ErrorsAreFun");

                    // Expecting 404
                    var aggEx = Assert.Throws<AggregateException>(() => connection.Start(host.Transport).Wait());

                    connection.Stop();

                    using (var ser = aggEx.GetError())
                    {
                        if (hostType == HostType.IISExpress)
                        {
                            Assert.Equal(System.Net.HttpStatusCode.InternalServerError, ser.StatusCode);
                        }
                        else
                        {
                            Assert.Equal(System.Net.HttpStatusCode.NotFound, ser.StatusCode);
                        }

                        Assert.NotNull(ser.ResponseBody);
                        Assert.NotNull(ser.Exception);
                    }
                }
            }
开发者ID:kppullin,项目名称:SignalR,代码行数:29,代码来源:ConnectionFacts.cs


示例5: TestClientConnectionSetUp

 public void TestClientConnectionSetUp()
 {
     mocks = new MockRepository();
     mockSocket = mocks.DynamicMock<iSocket.iSocket>();
     mockClient = mocks.DynamicMock<Client.iClient>();
     connection = new Client.Connection(mockClient);
     connection.sock = mockSocket;
 }
开发者ID:Carterj3,项目名称:Caesura,代码行数:8,代码来源:TestClientConnection.cs


示例6: CreateConnection

 protected Client.Connection CreateConnection(ITestHost host, string path)
 {
     var query = new Dictionary<string, string>();
     query["test"] = GetTestName();
     SetHostData(host, query);
     var connection = new Client.Connection(host.Url + path, query);
     connection.TraceWriter = host.ClientTraceOutput ?? connection.TraceWriter;
     return connection;
 }
开发者ID:hallco978,项目名称:SignalR,代码行数:9,代码来源:HostedTest.cs


示例7: ConnectionStateChangedEventIsCalledWithAppropriateArguments

        public void ConnectionStateChangedEventIsCalledWithAppropriateArguments()
        {
            var connection = new Client.Connection("http://test");

            connection.StateChanged += stateChange =>
            {
                Assert.Equal(ConnectionState.Disconnected, stateChange.OldState);
                Assert.Equal(ConnectionState.Connecting, stateChange.NewState);
            };

            Assert.True(((Client.IConnection)connection).ChangeState(ConnectionState.Disconnected, ConnectionState.Connecting));
        }
开发者ID:stirno,项目名称:SignalR,代码行数:12,代码来源:ConnectionFacts.cs


示例8: ClientGroupsSyncWithServerGroupsOnReconnectLongPolling

        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;
        }
开发者ID:rustd,项目名称:SignalR,代码行数:52,代码来源:StressRuns.cs


示例9: FailedNegotiateShouldNotBeActive

            public void FailedNegotiateShouldNotBeActive()
            {
                var connection = new Client.Connection("http://test");
                var transport = new Mock<IClientTransport>();
                transport.Setup(m => m.Negotiate(connection))
                         .Returns(TaskAsyncHelper.FromError<NegotiationResponse>(new InvalidOperationException("Something failed.")));

                var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
                var ex = aggEx.Unwrap();
                Assert.IsType(typeof(InvalidOperationException), ex);
                Assert.Equal("Something failed.", ex.Message);
                Assert.Equal(ConnectionState.Disconnected, connection.State);
            }
开发者ID:stirno,项目名称:SignalR,代码行数:13,代码来源:ConnectionFacts.cs


示例10: FarmDisconnectRaisesUncleanDisconnects

        public async Task FarmDisconnectRaisesUncleanDisconnects()
        {
            // Each node shares the same bus but are independent servers
            const int nodeCount = 3;
            var counters = new Infrastructure.PerformanceCounterManager();
            var configurationManager = new DefaultConfigurationManager();
            configurationManager.DisconnectTimeout = TimeSpan.FromSeconds(6);

            using (EnableDisposableTracing())
            using (var bus = new MessageBus(new StringMinifier(), new TraceManager(), counters, configurationManager, 5000))
            using (var loadBalancer = new LoadBalancer(nodeCount))
            {
                var broadcasters = new List<IConnection>();
                var disconnectCounter = new DisconnectCounter();
                loadBalancer.Configure(app =>
                {
                    var resolver = new DefaultDependencyResolver();

                    resolver.Register(typeof(IMessageBus), () => bus);
                    resolver.Register(typeof(IConfigurationManager), () => configurationManager);
                    resolver.Register(typeof(FarmConnection), () => new FarmConnection(disconnectCounter));

                    var connectionManager = resolver.Resolve<IConnectionManager>();
                    broadcasters.Add(connectionManager.GetConnectionContext<FarmConnection>().Connection);

                    app.MapSignalR<FarmConnection>("/echo", new ConnectionConfiguration
                    {
                        Resolver = resolver
                    });
                });

                var transport = new Client.Transports.LongPollingTransport(loadBalancer);
                var connection = new Client.Connection("http://goo/echo");

                await connection.Start(transport);

                for (int i = 0; i < nodeCount; i++)
                {
                    broadcasters[i].Broadcast(String.Format("From Node {0}: {1}", i, i + 1)).Wait();
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }

                ((Client.IConnection)connection).Disconnect();

                await Task.Delay(TimeSpan.FromTicks(TimeSpan.FromSeconds(5).Ticks * nodeCount));

                Assert.Equal(0, disconnectCounter.CleanDisconnectCount);
                Assert.Equal(3, disconnectCounter.UncleanDisconnectCount);
            }
        }
开发者ID:kietnha,项目名称:SignalR,代码行数:50,代码来源:FarmFacts.cs


示例11: VerifyThatChangingTheJsonSerializerWorks

        public void VerifyThatChangingTheJsonSerializerWorks()
        {
            var connection = new Client.Connection("http://test");

            var firstInstance = connection.JsonSerializer;

            connection.JsonSerializer = new Newtonsoft.Json.JsonSerializer
            {
                TypeNameHandling = Newtonsoft.Json.TypeNameHandling.All
            };

            var secondInstance = connection.JsonSerializer;

            Assert.NotSame(firstInstance, secondInstance);
        }
开发者ID:nirmana,项目名称:SignalR,代码行数:15,代码来源:ConnectionFacts.cs


示例12: ConnectionTraceIsProperlyFiltered

        public void ConnectionTraceIsProperlyFiltered()
        {
            var traceNumber = 0;
            var traceOutput = new StringBuilder();
            var traceWriter = new StringWriter(traceOutput);
            var connection = new Client.Connection("http://test");
            var timestampPattern = new Regex(@"^.* - ", RegexOptions.Multiline);

            Func<string> traceWithoutTimestamps = () =>
                timestampPattern.Replace(traceOutput.ToString(), String.Empty);

            Action traceAllLevels = () =>
            {
                connection.Trace(TraceLevels.Messages, "{0}: Message", ++traceNumber);
                connection.Trace(TraceLevels.Events, "{0}: Event", ++traceNumber);
                connection.Trace(TraceLevels.StateChanges, "{0}: State Change", ++traceNumber);
            };

            connection.TraceWriter = traceWriter;

            traceAllLevels();
            Assert.Equal("1: Message\r\n2: Event\r\n3: State Change\r\n", traceWithoutTimestamps());
            traceOutput.Clear();

            connection.TraceLevel = TraceLevels.All;
            traceAllLevels();
            Assert.Equal("4: Message\r\n5: Event\r\n6: State Change\r\n", traceWithoutTimestamps());
            traceOutput.Clear();

            connection.TraceLevel = TraceLevels.Messages;
            traceAllLevels();
            Assert.Equal("7: Message\r\n", traceWithoutTimestamps());
            traceOutput.Clear();

            connection.TraceLevel = TraceLevels.Events;
            traceAllLevels();
            Assert.Equal("11: Event\r\n", traceWithoutTimestamps());
            traceOutput.Clear();

            connection.TraceLevel = TraceLevels.StateChanges;
            traceAllLevels();
            Assert.Equal("15: State Change\r\n", traceWithoutTimestamps());
            traceOutput.Clear();

            connection.TraceLevel = TraceLevels.None;
            traceAllLevels();
            Assert.Equal(String.Empty, traceWithoutTimestamps());
        }
开发者ID:nirmana,项目名称:SignalR,代码行数:48,代码来源:ConnectionFacts.cs


示例13: NegotiatePassesClientProtocolCorrectly

        public void NegotiatePassesClientProtocolCorrectly(string clientProtocolParameter, string connectionQueryString)
        {
            var connection = new Client.Connection("http://test", connectionQueryString);

            try
            {
                connection.Start(new LongPollingTransport(new UrlInspectingHttpClient((url) =>
                {
                    Assert.True(url.Contains(clientProtocolParameter + connection.Protocol.ToString()));
                }))).Wait();
            }
            catch
            {
                // Swallow exceptions because the custom http client that we pass will throw unimplemented exceptions.
            }
        }
开发者ID:nirmana,项目名称:SignalR,代码行数:16,代码来源:ConnectionFacts.cs


示例14: GroupsAreNotReadOnConnectedAsync

            public void GroupsAreNotReadOnConnectedAsync()
            {
                var host = new MemoryHost();
                host.MapConnection<MyConnection>("/echo");

                var connection = new Client.Connection("http://foo/echo");
                connection.Groups = new List<string> { typeof(MyConnection).FullName + ".test" };
                connection.Received += data =>
                {
                    Assert.False(true, "Unexpectedly received data");
                };

                connection.Start(host).Wait();

                Thread.Sleep(TimeSpan.FromSeconds(10));
            }
开发者ID:ninjaAB,项目名称:SignalR,代码行数:16,代码来源:PersistentConnectionFacts.cs


示例15: Main

        private static void Main()
        {
            const string url = "http://localhost:8081/";

            var server = new Server(url);
            server.MapConnection<MyConnection>("/echo");
            server.Start();
            Console.WriteLine("Server running on {0}", url);

            var connection = new Client.Connection("http://localhost:8081/echo");
            connection.Received += Console.WriteLine;
            connection.StateChanged += change => Console.WriteLine(change.OldState + " => " + change.NewState);
            connection.Start().ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        Console.WriteLine("Faulted:{0}",
                                          task.Exception != null
                                              ? task.Exception.GetBaseException().ToString()
                                              : "Task Faulted");
                    }
                    else
                    {
                        Console.WriteLine("Successfully Connected");

                        try
                        {
                            while (true)
                            {
                                //Just a sample to test the concept
                                Console.WriteLine("\nCalling Server {0} @ {1}", connection.Url, DateTime.Now);
                                connection.Send("Hello Server");
                                Thread.Sleep(2000);
                            }
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception);
                        }
                    }
                });

            Console.ReadLine();
        }
开发者ID:Hdesai,项目名称:NLogToSignalR,代码行数:44,代码来源:Program.cs


示例16: ThrownWebExceptionShouldBeUnwrapped

            public void ThrownWebExceptionShouldBeUnwrapped()
            {
                var host = new MemoryHost();
                host.MapConnection<MyBadConnection>("/ErrorsAreFun");

                var connection = new Client.Connection("http://test/ErrorsAreFun");

                // Expecting 404
                var aggEx = Assert.Throws<AggregateException>(() => connection.Start(host).Wait());

                connection.Stop();

                using (var ser = aggEx.GetError())
                {
                    Assert.Equal(ser.StatusCode, HttpStatusCode.NotFound);
                    Assert.NotNull(ser.ResponseBody);
                    Assert.NotNull(ser.Exception);
                }
            }
开发者ID:kpmrafeeq,项目名称:SignalR,代码行数:19,代码来源:ConnectionFacts.cs


示例17: FailedStartShouldNotBeActive

            public void FailedStartShouldNotBeActive()
            {
                var connection = new Client.Connection("http://test");
                var transport = new Mock<IClientTransport>();
                transport.Setup(m => m.Negotiate(connection))
                         .Returns(TaskAsyncHelper.FromResult(new NegotiationResponse
                         {
                             ProtocolVersion = "1.2",
                             ConnectionId = "Something"
                         }));

                transport.Setup(m => m.Start(connection, null, It.IsAny<CancellationToken>()))
                         .Returns(TaskAsyncHelper.FromError(new InvalidOperationException("Something failed.")));

                var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait());
                var ex = aggEx.Unwrap();
                Assert.IsType(typeof(InvalidOperationException), ex);
                Assert.Equal("Something failed.", ex.Message);
                Assert.Equal(ConnectionState.Disconnected, connection.State);
            }
开发者ID:stirno,项目名称:SignalR,代码行数:20,代码来源:ConnectionFacts.cs


示例18: ClientGroupsSyncWithServerGroupsOnReconnectWhenNotRejoiningGroups

            public void ClientGroupsSyncWithServerGroupsOnReconnectWhenNotRejoiningGroups(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 + "/groups");
                    var inGroupOnReconnect = new List<bool>();
                    var wh = new ManualResetEventSlim();

                    connection.Received += message =>
                    {
                        Assert.Equal("Reconnected", message);
                        inGroupOnReconnect.Add(!connection.Groups.Contains(typeof(MyGroupConnection).FullName + ".test"));
                        inGroupOnReconnect.Add(connection.Groups.Contains(typeof(MyGroupConnection).FullName + ".test2"));
                        wh.Set();
                    };

                    connection.Reconnected += () =>
                    {
                        connection.Send(new { type = 1, group = "test2" }).Wait();
                        connection.Send(new { type = 3, group = "test2", 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(5));

                    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();
                }
            }
开发者ID:kppullin,项目名称:SignalR,代码行数:41,代码来源:PersistentConnectionFacts.cs


示例19: GroupsRejoinedWhenOnRejoiningGroupsOverridden

            public void GroupsRejoinedWhenOnRejoiningGroupsOverridden(HostType hostType, TransportType transportType)
            {
                using (var host = CreateHost(hostType, transportType))
                {
                    host.Initialize(keepAlive: null,
                                    disconnectTimeout: 6,
                                    connectionTimeout: 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.SendWithTimeout(new { type = 1, group = "test" });

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

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

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

                    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]);
                }
            }
开发者ID:elylucas,项目名称:SignalR,代码行数:39,代码来源:PersistentConnectionFacts.cs


示例20: DisconnectFiresForPersistentConnectionWhenClientGoesAway

        public void DisconnectFiresForPersistentConnectionWhenClientGoesAway()
        {
            var host = new MemoryHost();
            host.MapConnection<MyConnection>("/echo");
            host.Configuration.DisconnectTimeout = TimeSpan.Zero;
            host.Configuration.HeartBeatInterval = TimeSpan.FromSeconds(5);
            var connectWh = new ManualResetEventSlim();
            var disconnectWh = new ManualResetEventSlim();
            host.DependencyResolver.Register(typeof(MyConnection), () => new MyConnection(connectWh, disconnectWh));
            var connection = new Client.Connection("http://foo/echo");

            // Maximum wait time for disconnect to fire (3 heart beat intervals)
            var disconnectWait = TimeSpan.FromTicks(host.Configuration.HeartBeatInterval.Ticks * 3);

            connection.Start(host).Wait();

            Assert.True(connectWh.Wait(TimeSpan.FromSeconds(10)), "Connect never fired");

            connection.Stop();

            Assert.True(disconnectWh.Wait(disconnectWait), "Disconnect never fired");
        }
开发者ID:paulduran,项目名称:SignalR,代码行数:22,代码来源:DisconnectFacts.cs



注:本文中的Client.Connection类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Hubs.HubConnection类代码示例发布时间:2022-05-24
下一篇:
C# Client类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap