本文整理汇总了C#中System.Net.WebSockets.ClientWebSocket.ConnectAsync方法的典型用法代码示例。如果您正苦于以下问题:C# ClientWebSocket.ConnectAsync方法的具体用法?C# ClientWebSocket.ConnectAsync怎么用?C# ClientWebSocket.ConnectAsync使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebSockets.ClientWebSocket
的用法示例。
在下文中一共展示了ClientWebSocket.ConnectAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestWebSockets
private void TestWebSockets()
{
var socket = new ClientWebSocket();
Console.WriteLine("Connecting");
socket.ConnectAsync(new Uri("wss://echo.websocket.org"), CancellationToken.None).Wait();
Console.WriteLine("Sending");
socket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Hello")), WebSocketMessageType.Text, true, CancellationToken.None).Wait();
var buffer = new byte[1024];
Console.WriteLine("Receiving");
var result = socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None).Result;
Console.WriteLine($"Recieved: {Encoding.UTF8.GetString(buffer, 0, result.Count)}");
}
示例2: 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();
}
}
}
示例3: 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.");
}
}
示例4: 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();
}
示例5: Run
public static async Task Run(Control control, Bitmap bitmap)
{
using (var webSocket = new ClientWebSocket())
{
var stream = new WebSocketStream(webSocket);
await webSocket.ConnectAsync(new Uri("ws://localhost:5050/ws"), CancellationToken.None);
await DispatchStartAsync(control, bitmap, stream);
while (true)
{
await DispatchDeltaAsync(control, bitmap, stream);
}
}
}
示例6: RunSample
public static async Task RunSample()
{
ClientWebSocket websocket = new ClientWebSocket();
string url = "ws://localhost:7000/";
Console.WriteLine("Connecting to: " + url);
await websocket.ConnectAsync(new Uri(url), CancellationToken.None);
int seed = 20000;
Task[] taskList = new Task[seed];
Stopwatch sw = new Stopwatch();
sw.Restart();
for (var i = 0; i < seed; i++)
{
//taskList[i] = Send(websocket);
await Send(websocket);
}
//Task.WaitAll(taskList);
sw.Stop();
Console.WriteLine("seed:{0}, time:{1}", seed, sw.ElapsedMilliseconds);
//if (result.CloseStatus.HasValue)
//{
// Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
//}
//else
//{
// Console.WriteLine("Received message: " + Encoding.UTF8.GetString(incomingData, 0, result.Count));
//}
}
示例7: 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();
}
}
}
示例8: WebsocketBasic
public async Task WebsocketBasic(HostType hostType)
{
using (ApplicationDeployer deployer = new ApplicationDeployer())
{
string applicationUrl = deployer.Deploy(hostType, WebsocketBasicConfiguration);
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(applicationUrl.Replace("http://", "ws://")), CancellationToken.None);
var receiveBody = new byte[100];
for (int i = 0; i < 4; i++)
{
var message = "Message " + i.ToString();
byte[] sendBody = Encoding.UTF8.GetBytes(message);
await client.SendAsync(new ArraySegment<byte>(sendBody), WebSocketMessageType.Text, true, CancellationToken.None);
var receiveResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);
Assert.Equal(WebSocketMessageType.Text, receiveResult.MessageType);
Assert.True(receiveResult.EndOfMessage);
Assert.Equal(sendBody.Length, receiveResult.Count);
Assert.Equal(message, Encoding.UTF8.GetString(receiveBody, 0, receiveResult.Count));
}
}
}
}
示例9: RunSample
public static async Task RunSample()
{
ClientWebSocket websocket = new ClientWebSocket();
string url = "ws://localhost:5000/";
Console.WriteLine("Connecting to: " + url);
await websocket.ConnectAsync(new Uri(url), CancellationToken.None);
string message = "Hello World";
Console.WriteLine("Sending message: " + message);
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
await websocket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true, CancellationToken.None);
byte[] incomingData = new byte[1024];
WebSocketReceiveResult result = await websocket.ReceiveAsync(new ArraySegment<byte>(incomingData), CancellationToken.None);
if (result.CloseStatus.HasValue)
{
Console.WriteLine("Closed; Status: " + result.CloseStatus + ", " + result.CloseStatusDescription);
}
else
{
Console.WriteLine("Received message: " + Encoding.UTF8.GetString(incomingData, 0, result.Count));
}
}
示例10: ConnectAsync
internal async Task<IAsyncTransport> ConnectAsync(Address address, Action<ClientWebSocketOptions> options)
{
Uri uri = new UriBuilder()
{
Scheme = address.Scheme,
Port = GetDefaultPort(address.Scheme, address.Port),
Host = address.Host,
Path = address.Path
}.Uri;
ClientWebSocket cws = new ClientWebSocket();
cws.Options.AddSubProtocol(WebSocketSubProtocol);
if (options != null)
{
options(cws.Options);
}
await cws.ConnectAsync(uri, CancellationToken.None);
if (cws.SubProtocol != WebSocketSubProtocol)
{
cws.Abort();
throw new NotSupportedException(
string.Format(
CultureInfo.InvariantCulture,
"WebSocket SubProtocol used by the host is not the same that was requested: {0}",
cws.SubProtocol ?? "<null>"));
}
this.webSocket = cws;
return this;
}
示例11: 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();
}
示例12: TestConnectWebSocket
public async void TestConnectWebSocket()
{
if (TestHelper.IsMono)
{
Assert.Inconclusive("Mono doesn't have support to WebSockets");
}
Assert.IsNotNull(WebServer.Module<WebSocketsModule>(), "WebServer has WebSocketsModule");
Assert.AreEqual(WebServer.Module<WebSocketsModule>().Handlers.Count, 1, "WebSocketModule has one handler");
var clientSocket = new ClientWebSocket();
var ct = new CancellationTokenSource();
await clientSocket.ConnectAsync(new Uri(Resources.WsServerAddress + "/test"), ct.Token);
Assert.AreEqual(clientSocket.State, WebSocketState.Open, "Connection is open");
var message = new ArraySegment<byte>(System.Text.Encoding.Default.GetBytes("HOLA"));
var buffer = new ArraySegment<byte>(new byte[1024]);
await clientSocket.SendAsync(message, WebSocketMessageType.Text, true, ct.Token);
var result = await clientSocket.ReceiveAsync(buffer, ct.Token);
Assert.IsTrue(result.EndOfMessage);
Assert.IsTrue(System.Text.Encoding.UTF8.GetString(buffer.Array).TrimEnd((char) 0) == "WELCOME");
}
示例13: ListenAsync
public async Task ListenAsync()
{
var socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri(ServerUrl.Replace("http://", "ws://")), CancellationToken.None);
// listen for updates
await Receive(socket);
}
示例14: ConnectPusher
public void ConnectPusher()
{
_ws = new ClientWebSocket();
_ws.ConnectAsync(new Uri("wss://ws.pusherapp.com/app/de504dc5763aeef9ff52?client=PC-Orbit&version=1.0&protocol=7"), _source.Token).Wait();
_connected = true;
ThreadingHelper.Thread(OnReceive).Launch();
}
示例15: Main
protected override void Main()
{
if (Environment.OSVersion.Version < new Version(6, 2))
{
TraceError(Text.LabRequiresWindows8OrHigher);
return;
}
const int port = 5494;
string subProtocol = GetType().Name;
var userMessages = new BehaviorSubject<string>(null);
var client = new ClientWebSocket();
client.Options.AddSubProtocol(subProtocol);
using (client)
using (var cancel = new CancellationDisposable())
using (ObservableHttpListener
.StartWebSockets(new IPEndPoint(IPAddress.Loopback, port), subProtocol)
.Subscribe(
async request =>
{
using (var socket = request.WebSocket)
{
try
{
var message = await ReceiveMessageAsync(socket, cancel.Token);
await SendMessageAsync("You sent \"" + message + "\"", socket, cancel.Token);
await ReceiveCloseMessageAsync(socket, cancel.Token);
}
catch (OperationCanceledException)
{
}
}
},
TraceError))
using ((from _ in client.ConnectAsync(new Uri("ws://localhost:" + port), cancel.Token).ToObservable()
.Do(_ => TraceLine(Environment.NewLine + "(Connected to host on sub-protocol \"{0}\")", client.SubProtocol))
from message in userMessages.Where(m => m != null).Take(1)
from __ in SendMessageAsync(message, client, cancel.Token).ToObservable()
from response in ReceiveMessageAsync(client, cancel.Token).ToObservable()
.Do(___ => client.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", cancel.Token))
select response)
.Subscribe(
response => TraceLine("Response: {0}", response),
TraceError,
() => TraceLine("{0}: {1}", Text.Client, Text.Done)))
{
userMessages.OnNext(UserInput("{0}> ", Instructions.EnterAMessage));
TraceStatus(Instructions.PressAnyKeyToCancel);
WaitForKey();
}
}