本文整理汇总了C#中System.Net.WebSockets.ClientWebSocket.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# ClientWebSocket.Dispose方法的具体用法?C# ClientWebSocket.Dispose怎么用?C# ClientWebSocket.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebSockets.ClientWebSocket
的用法示例。
在下文中一共展示了ClientWebSocket.Dispose方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: BasicRoundTrip
public void BasicRoundTrip()
{
var serializer = new JsonCommonSerializer();
var port = new Random().Next(6000, 60000);
var options = new WebSocketListenerOptions();
options.SubProtocols = new[] { "SignalR" };
var listener = new WebSocketListener(new IPEndPoint(IPAddress.Loopback, port), options);
var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(listener);
listener.Standards.RegisterStandard(rfc6455);
var serverTransport = listener.GenerateTransportSource();
var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
serverRouter.AddService<IMyService>(new MyService());
listener.Start();
var client = new ClientWebSocket();
client.Options.AddSubProtocol("SignalR");
var clientTransport = client.GenerateTransportSource();
var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
var proxy = clientRouter.AddInterface<IMyService>();
client.ConnectAsync(new Uri("ws://localhost:" + port + "/"), CancellationToken.None).Wait();
var result = proxy.Add(3, 4).Result;
Assert.Equal(7, result);
clientRouter.Dispose();
clientTransport.Dispose();
client.Dispose();
serverRouter.Dispose();
serverTransport.Dispose();
listener.Dispose();
}
示例2: BasicRoundTrip
public void BasicRoundTrip()
{
var serializer = new JsonCommonSerializer();
var server = new HttpListener();
server.Prefixes.Add("http://localhost:20000/");
server.Start();
var serverTransport = server.GenerateTransportSource();
var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
serverRouter.AddService<IMyService>(new MyService());
var client = new ClientWebSocket();
client.Options.SetBuffer(8192, 8192);
var clientTransport = client.GenerateTransportSource();
var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
var proxy = clientRouter.AddInterface<IMyService>();
client.ConnectAsync(new Uri("ws://localhost:20000/"), CancellationToken.None).Wait();
var result = proxy.Add(3, 4).Result;
Assert.Equal(7, result);
clientRouter.Dispose();
clientTransport.Dispose();
client.Dispose();
serverRouter.Dispose();
serverTransport.Dispose();
server.Stop();
server.Close();
}
示例3: Connect
public static async Task Connect(string uri)
{
ClientWebSocket webSocket = null;
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
await Task.WhenAll(Receive(webSocket), Send(webSocket));
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex);
}
finally
{
if (webSocket != null)
webSocket.Dispose();
Console.WriteLine();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
示例4: Connect
public virtual Stream Connect(Uri uri, bool requireAuthentication) {
// IIS starts python.exe processes lazily on the first incoming request, and will terminate them after a period
// of inactivity, making it impossible to attach. So before trying to connect to the debugger, "ping" the website
// via HTTP to ensure that we have something to connect to.
try {
var httpRequest = WebRequest.Create(new UriBuilder(uri) { Scheme = "http", Port = -1, Path = "/" }.Uri);
httpRequest.Method = WebRequestMethods.Http.Head;
httpRequest.Timeout = 5000;
httpRequest.GetResponse().Dispose();
} catch (WebException) {
// If it fails or times out, just go ahead and try to connect anyway, and rely on normal error reporting path.
}
var webSocket = new ClientWebSocket();
try {
webSocket.ConnectAsync(uri, CancellationToken.None).GetAwaiter().GetResult();
var stream = new WebSocketStream(webSocket, ownsSocket: true);
webSocket = null;
return stream;
} catch (WebSocketException ex) {
throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
} catch (IOException ex) {
throw new ConnectionException(ConnErrorMessages.RemoteNetworkError, ex);
} catch (PlatformNotSupportedException ex) {
throw new ConnectionException(ConnErrorMessages.RemoteUnsupportedTransport, ex);
} finally {
if (webSocket != null) {
webSocket.Dispose();
}
}
}
示例5: ConnectAndStartReceivingToWebSocket
public async void ConnectAndStartReceivingToWebSocket()
{
ClientWebSocket webSocket = null;
var uncontext = new Uri(_wsLiteratureUncontextCom);
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(uncontext, CancellationToken.None);
await Receive(webSocket);
}
catch (Exception ex)
{
Console.WriteLine("Exception: {0}", ex);
}
finally
{
if (webSocket != null)
{
webSocket.Dispose();
UncontextedData.OnCompleted();
}
Console.WriteLine("Closed websocket.");
}
}
示例6: ConnectAsync
public async Task ConnectAsync(string url)
{
await DisconnectAsync();
_disconnectToken = new CancellationTokenSource();
var cancelToken = _disconnectToken.Token;
_webSocket = new ClientWebSocket();
_webSocket.Options.KeepAliveInterval = TimeSpan.Zero;
await _webSocket.ConnectAsync(new Uri(url), cancelToken);
_host = url;
if (_isDebug)
RaiseOnDebugMessage(DebugMessageType.Connection, $"Connected.");
OnConnect();
_lastHeartbeat = DateTime.UtcNow;
_task = Task.Factory.ContinueWhenAll(CreateTasks(), x =>
{
if (_isDebug)
RaiseOnDebugMessage(DebugMessageType.Connection, $"Disconnected.");
//Do not clean up until all tasks have ended
OnDisconnect();
_disconnectToken.Dispose();
_disconnectToken = null;
_wasDisconnectedUnexpected = false;
//Clear send queue
_heartbeatInterval = 0;
_lastHeartbeat = DateTime.MinValue;
_webSocket.Dispose();
_webSocket = null;
byte[] ignored;
while (_sendQueue.TryDequeue(out ignored)) { }
if (_isConnected)
{
_isConnected = false;
RaiseDisconnected(_wasDisconnectedUnexpected);
}
_task = null;
});
}
示例7: RefreshInternal
private void RefreshInternal(string debuggerUrl)
{
if (string.IsNullOrEmpty(debuggerUrl))
return;
ClientWebSocket connection = new ClientWebSocket();
connection.ConnectAsync(new Uri(debuggerUrl), _token).Wait();
PageReloadRequest request = new PageReloadRequest();
string rawRequest = request.ToJson();
var data = new ArraySegment<byte>(Encoding.UTF8.GetBytes(rawRequest));
connection.SendAsync(data, WebSocketMessageType.Text, true, _token).Wait();
var buffer = new ArraySegment<byte>(new byte[1024]);
Task<WebSocketReceiveResult> receiveAsync = connection.ReceiveAsync(buffer, _token);
receiveAsync.Wait();
string rawResponse = Encoding.UTF8.GetString(buffer.Array, 0, receiveAsync.Result.Count);
DebugProtocolResponse response = rawResponse.FromJson<DebugProtocolResponse>();
if (null != response.Error)
{
Trace.TraceWarning("Browser returned an error as a response to reload request: {0}",
response.Error.Message);
}
connection.Dispose();
}
示例8: AuthorizationTest
public void AuthorizationTest()
{
using (WebApp.Start(new StartOptions("http://localhost:8989"), startup =>
{
startup.MapOwinFleckRoute("/fleck", connection =>
{
var id = ConfigureIntegrationTestConnectionAndGetId(connection);
connection.OnAuthenticateRequest = () =>
{
var result = id % 2 == 1;
Send(id, $"Auth {id}: {result}");
return result;
};
});
}))
using (var client1 = new ClientWebSocket())
using (var client2 = new ClientWebSocket())
using (var client3 = new ClientWebSocket())
{
client1.ConnectAsync(new Uri("ws://localhost:8989/fleck"), CancellationToken.None).Wait();
try
{
client2.ConnectAsync(new Uri("ws://localhost:8989/fleck"), CancellationToken.None).Wait();
Assert.Fail("Client 2 should not be unauthorized");
}
catch (AggregateException ex)
{
Assert.AreEqual("Unable to connect to the remote server", ex.InnerException.Message);
}
client3.ConnectAsync(new Uri("ws://localhost:8989/fleck"), CancellationToken.None).Wait();
var bytes3 = new byte[1024];
var segment3 = new ArraySegment<byte>(bytes3);
var receive3 = client3.ReceiveAsync(segment3, CancellationToken.None);
var message1 = "Hello world";
var bytes1 = Encoding.UTF8.GetBytes(message1);
var segment1 = new ArraySegment<byte>(bytes1);
client1.SendAsync(segment1, WebSocketMessageType.Text, true, CancellationToken.None).Wait();
var result3 = receive3.Result;
Assert.AreEqual(WebSocketMessageType.Text, result3.MessageType);
var message3 = Encoding.UTF8.GetString(segment3.Array, 0, result3.Count);
Assert.AreEqual(message3, "User 1: Hello world");
client3.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
client3.Dispose();
Task.Delay(100).Wait();
client1.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
client1.Dispose();
Task.Delay(100).Wait();
}
var messages = DequeueMessages();
Assert.AreEqual(8, messages.Count);
Assert.AreEqual("Auth 1: True", messages[0]);
Assert.AreEqual("Open: 1", messages[1]);
Assert.AreEqual("Auth 2: False", messages[2]);
Assert.AreEqual("Auth 3: True", messages[3]);
Assert.AreEqual("Open: 3", messages[4]);
Assert.AreEqual("User 1: Hello world", messages[5]);
Assert.AreEqual("Close: 3", messages[6]);
Assert.AreEqual("Close: 1", messages[7]);
}
示例9: SendIntegrationTestMessages
protected void SendIntegrationTestMessages()
{
using (var client1 = new ClientWebSocket())
using (var client2 = new ClientWebSocket())
{
client1.ConnectAsync(new Uri("ws://localhost:8989"), CancellationToken.None).Wait();
Task.Delay(100).Wait();
client2.ConnectAsync(new Uri("ws://localhost:8989"), CancellationToken.None).Wait();
Task.Delay(100).Wait();
var bytes2 = new byte[1024];
var segment2 = new ArraySegment<byte>(bytes2);
var receive2 = client2.ReceiveAsync(segment2, CancellationToken.None);
var message1 = "Hello world";
var bytes1 = Encoding.UTF8.GetBytes(message1);
var segment1 = new ArraySegment<byte>(bytes1);
client1.SendAsync(segment1, WebSocketMessageType.Text, true, CancellationToken.None).Wait();
Task.Delay(100).Wait();
var result2 = receive2.Result;
Assert.AreEqual(WebSocketMessageType.Text, result2.MessageType);
var message3 = Encoding.UTF8.GetString(segment2.Array, 0, result2.Count);
Assert.AreEqual("User 1: Hello world", message3);
client2.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
client2.Dispose();
Task.Delay(100).Wait();
client1.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
client1.Dispose();
Task.Delay(100).Wait();
}
}
示例10: Benchmark
public void Benchmark()
{
var serializer = new JsonCommonSerializer();
var port = new Random().Next(30000, 60000);
var options = new WebSocketListenerOptions();
options.SubProtocols = new[] { "SignalR" };
var listener = new WebSocketListener(new IPEndPoint(IPAddress.Loopback, port), options);
var rfc6455 = new vtortola.WebSockets.Rfc6455.WebSocketFactoryRfc6455(listener);
listener.Standards.RegisterStandard(rfc6455);
var serverTransport = listener.GenerateTransportSource();
var serverRouter = new DefaultMessageRouter(serverTransport, serializer);
serverRouter.AddService<ISumService>(new SumService());
listener.Start();
var client = new ClientWebSocket();
client.Options.AddSubProtocol("SignalR");
var clientTransport = client.GenerateTransportSource();
var clientRouter = new DefaultMessageRouter(clientTransport, serializer);
var proxy = clientRouter.AddInterface<ISumService>();
client.ConnectAsync(new Uri("ws://localhost:" + port + "/"), CancellationToken.None).Wait();
const int randCnt = 100;
var rand = new Random(42);
var randoms = new int[randCnt];
for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
var sw = new Stopwatch();
long timeFromClient = 0, timeToClient = 0;
const int cnt = 1000;
for (int j = 0; j < cnt; j++)
{
sw.Start();
var sum = proxy.Sum(randoms).Result;
sw.Stop();
Assert.Equal(randoms.Sum(), sum);
for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000);
var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result;
timeFromClient += times.Item1;
timeToClient += Stopwatch.GetTimestamp() - times.Item2;
}
_testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds);
_testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10);
_testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10);
sw.Reset();
var tree = new SumServiceTree();
SumServiceTree.FillTree(tree, rand, 2);
_testOutputHelper.WriteLine("Starting large message transfer.");
sw.Start();
var result = proxy.Increment(tree).Result;
sw.Stop();
Assert.Equal(tree.Leaf + 1, result.Leaf);
_testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds);
clientRouter.Dispose();
clientTransport.Dispose();
client.Dispose();
serverRouter.Dispose();
serverTransport.Dispose();
listener.Dispose();
}
示例11: Connect
public async Task Connect(string uri)
{
//connect to steam account
client = new SteamClient();
manager = new CallbackManager(client);
user = client.GetHandler<SteamUser>();
new Callback<SteamClient.ConnectedCallback>(OnConnected, manager);
new Callback<SteamUser.LoggedOnCallback>(OnLoggedOn, manager);
new Callback<SteamClient.DisconnectedCallback>(OnDisconnected, manager);
new Callback<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth, manager);
client.Connect();
isRunning = true;
while (isRunning)
{
manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
}
//Override jpg for map.
if (MapOverrrideBox.Checked)
{
MapImage.LoadAsync(MapOverRideUrlBox.Text);
}
else
{
MapImage.LoadAsync("http://" + ServerIPBox.Text + ":" + ServerPortBox.Text + "/map.jpg");
}
//connect to WS chat server
try
{
webSocket = new ClientWebSocket();
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
await Task.WhenAll(Receive(webSocket), Send(webSocket, ""));
}
catch (Exception ex)
{
this.SetText("Error: " + ex.Message );
}
finally
{
if (webSocket != null)
webSocket.Dispose();
}
}