本文整理汇总了C#中System.Net.WebSockets.ClientWebSocket.ReceiveAsync方法的典型用法代码示例。如果您正苦于以下问题:C# ClientWebSocket.ReceiveAsync方法的具体用法?C# ClientWebSocket.ReceiveAsync怎么用?C# ClientWebSocket.ReceiveAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebSockets.ClientWebSocket
的用法示例。
在下文中一共展示了ClientWebSocket.ReceiveAsync方法的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: 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");
}
示例3: 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));
}
}
}
}
示例4: 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));
}
}
示例5: ReceiveMessages
private async Task ReceiveMessages(ClientWebSocket socket,string msg, int total)
{
var maxMessageSize = 1024;
var receiveBuffer = new byte[maxMessageSize];
for (var i = 0; i < 10; i++)
{
var ret = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
if (ret.MessageType != WebSocketMessageType.Text) continue;
var count = ret.Count;
while (!ret.EndOfMessage)
{
ret = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer, count, maxMessageSize - count), CancellationToken.None);
count += ret.Count;
}
var receivedString = Encoding.UTF8.GetString(receiveBuffer, 0, count);
Trace.WriteLine(receivedString);
Interlocked.Increment(ref _counter);
}
}
示例6: Send
public static async Task Send(ClientWebSocket websocket)
{
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);
}
示例7: startRunner
private static async Task startRunner()
{
var socketUrl = await getSocketUrl();
ClientWebSocket ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri($"ws://{socketUrl}"), CancellationToken.None);
var buffer = new byte[1024 * 10];
await send(ws, new CreateNewGameRequestSocketMessage() { GameType = "sevens" });
while (true)
{
var segment = new ArraySegment<byte>(buffer);
var result = await ws.ReceiveAsync(segment, CancellationToken.None);
switch (result.MessageType)
{
case WebSocketMessageType.Binary:
byte[] bytes = new byte[result.Count];
Array.ConstrainedCopy(segment.Array, 0, bytes, 0, result.Count);
var obj = Serializer.Deserialize(bytes);
if (obj is GameStartedSocketMessage)
{
totalGames++;
games++;
}
else if (obj is AskQuestionSocketMessage)
{
var answerQ = (AskQuestionSocketMessage)obj;
await send(ws, new AnswerQuestionSocketMessage()
{
AnswerIndex = (short)(answerQ.Answers.Length > 1 ? 1 : 0)
});
totalAnswers++;
}
else if (obj is GameOverSocketMessage)
{
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
games--;
return;
}
break;
case WebSocketMessageType.Close:
await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
示例8: Run
static async Task Run()
{
var ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri("ws://localhost:8088"), CancellationToken.None);
byte[] buf = new byte[4096];
var seg = new ArraySegment<byte>(buf, 0, buf.Length);
var r1 = await ws.ReceiveAsync(seg, CancellationToken.None);
string id = UTF8Encoding.UTF8.GetString(buf, 0, r1.Count);
Console.WriteLine("SessionId=" + id);
for (int i = 0; i < 20; i++)
{
var msg = UTF8Encoding.UTF8.GetBytes("Send(" + i + ")");
await ws.SendAsync(new ArraySegment<byte>(msg, 0, msg.Length), WebSocketMessageType.Text, true, CancellationToken.None);
var rcv = await ws.ReceiveAsync(seg, CancellationToken.None);
string response = UTF8Encoding.UTF8.GetString(buf, 0, rcv.Count);
Console.WriteLine("Response=" + response);
Thread.Sleep(2000);
}
}
示例9: Receive
private static async Task Receive(ClientWebSocket webSocket)
{
byte[] buffer = new byte[receiveChunkSize];
while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
LogStatus(true, buffer, result.Count);
}
}
}
示例10: ReadEventsAsync
private async Task ReadEventsAsync()
{
var socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri("ws://localhost:7070/events"), CancellationToken.None);
while (true)
{
var buffer = new byte[1024];
var segment = new ArraySegment<byte>(buffer);
var result = await socket.ReceiveAsync(segment, CancellationToken.None);
var data = Encoding.UTF8.GetString(segment.Array, 0, result.Count);
Debug.WriteLine(data);
}
}
示例11: ReceiveWebsocketMessageAndAppend
private static void ReceiveWebsocketMessageAndAppend(ClientWebSocket client, List<String> messages)
{
var receiveBuffer = new byte[1024];
var receiveBufferSegment = new ArraySegment<byte>(receiveBuffer);
try
{
var result = client.ReceiveAsync(receiveBufferSegment, CancellationToken.None).Result;
if (result.Count > 0)
{
var message = Encoding.Default.GetString(receiveBuffer.Take(result.Count).ToArray());
if (message.Contains("error"))
{
throw new Exception("websocket returned an error message");
}
messages.Add(message);
}
}
catch (Exception) { }
}
示例12: Receive
// Define other methods and classes here
private async Task Receive(ClientWebSocket webSocket)
{
var buffer = new byte[64];
while (webSocket.State == WebSocketState.Open)
{
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
DeserializeAndEnqueue(buffer, result.Count);
}
//if(Console.KeyAvailable)
// break;
}
}
示例13: EndToEnd_ConnectAndClose_Success
public async Task EndToEnd_ConnectAndClose_Success()
{
OwinHttpListener listener = CreateServer(env =>
{
var accept = (WebSocketAccept)env["websocket.Accept"];
Assert.NotNull(accept);
accept(
null,
async wsEnv =>
{
var sendAsync1 = wsEnv.Get<WebSocketSendAsync>("websocket.SendAsync");
var receiveAsync1 = wsEnv.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
var closeAsync1 = wsEnv.Get<WebSocketCloseAsync>("websocket.CloseAsync");
var buffer1 = new ArraySegment<byte>(new byte[10]);
await receiveAsync1(buffer1, CancellationToken.None);
await closeAsync1((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
});
return TaskHelpers.Completed();
},
HttpServerAddress);
using (listener)
{
using (var client = new ClientWebSocket())
{
await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);
await client.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), CancellationToken.None);
Assert.Equal(WebSocketCloseStatus.NormalClosure, readResult.CloseStatus);
Assert.Equal("Closing", readResult.CloseStatusDescription);
Assert.Equal(0, readResult.Count);
Assert.True(readResult.EndOfMessage);
Assert.Equal(WebSocketMessageType.Close, readResult.MessageType);
}
}
}
示例14: Receive
private async Task Receive(ClientWebSocket socket)
{
var buffer = new byte[2048];
while (socket.State == WebSocketState.Open)
{
var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
else
{
var json = Encoding.ASCII.GetString(buffer).TrimEnd('\0');
var notification = JsonConvert.DeserializeObject<WebSocketClientNotification>(json);
NotificationReceived?.Invoke(this, new WebSocketClientNotificationEventArgs(notification));
Array.Clear(buffer,0,buffer.Length);
}
}
}
示例15: Subscribe
public async Task Subscribe(CancellationToken cancel)
{
byte[] buffer = new byte[1024 * 1024];
ArraySegment<byte> segment = new ArraySegment<byte>(buffer);
ByteString currentRecord = await this.store.GetLastTransaction();
while (!cancel.IsCancellationRequested)
{
try
{
ClientWebSocket socket = new ClientWebSocket();
this.endpoint.Query = string.Format("from={0}", currentRecord.ToString());
logger.LogInformation("Connecting to {0}", this.endpoint.Uri);
await socket.ConnectAsync(this.endpoint.Uri, cancel);
while (true)
{
WebSocketReceiveResult result = await socket.ReceiveAsync(segment, cancel);
if (result.MessageType == WebSocketMessageType.Close)
break;
ByteString record = new ByteString(buffer.Take(result.Count));
await store.AddTransactions(new[] { record });
currentRecord = new ByteString(MessageSerializer.ComputeHash(record.ToByteArray()));
}
}
catch (Exception exception)
{
logger.LogError("Error in the stream subscriber: {0}", exception.ToString());
}
await Task.Delay(TimeSpan.FromMinutes(1));
}
}