本文整理汇总了C#中Client.Connection.Start方法的典型用法代码示例。如果您正苦于以下问题:C# Client.Connection.Start方法的具体用法?C# Client.Connection.Start怎么用?C# Client.Connection.Start使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Client.Connection
的用法示例。
在下文中一共展示了Client.Connection.Start方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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]);
}
}
示例2: 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);
}
}
}
示例3: 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;
}
示例4: 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);
}
示例5: 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);
}
}
示例6: 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.
}
}
示例7: 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));
}
示例8: 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();
}
示例9: 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);
}
}
示例10: 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);
}
示例11: ClientGroupsSyncWithServerGroupsOnReconnect
public void ClientGroupsSyncWithServerGroupsOnReconnect(HostType hostType, TransportType transportType)
{
using (var host = CreateHost(hostType, transportType))
{
host.Initialize(keepAlive: 0,
connectionTimeout: 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.SendWithTimeout(new { type = 3, group = "test", message = "Reconnected" });
};
connection.Start(host.Transport).Wait();
// Join the group
connection.SendWithTimeout(new { type = 1, group = "test" });
// 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();
}
}
示例12: 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");
}
示例13: SendCanBeCalledAfterStateChangedEvent
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.SendWithTimeout("");
}
};
connection.Start(host.Transport).Wait();
Thread.Sleep(TimeSpan.FromSeconds(5));
connection.Stop();
Debug.WriteLine(String.Join(", ", results));
Assert.Equal(4, results.Count);
}
}
示例14: ReconnectFiresAfterTimeOutSSE
public void ReconnectFiresAfterTimeOutSSE()
{
var host = new MemoryHost();
var conn = new MyReconnect();
host.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(5);
host.Configuration.HeartBeatInterval = TimeSpan.FromSeconds(1);
host.DependencyResolver.Register(typeof(MyReconnect), () => conn);
host.MapConnection<MyReconnect>("/endpoint");
var connection = new Client.Connection("http://foo/endpoint");
connection.Start(host).Wait();
Thread.Sleep(TimeSpan.FromSeconds(15));
Assert.Equal(2, conn.Reconnects);
}
示例15: SendToAllButCaller
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();
}