本文整理汇总了C#中System.Net.WebSockets.WebSocket.CloseAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebSocket.CloseAsync方法的具体用法?C# WebSocket.CloseAsync怎么用?C# WebSocket.CloseAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.WebSockets.WebSocket
的用法示例。
在下文中一共展示了WebSocket.CloseAsync方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ProcessWebSocket
public async Task ProcessWebSocket(HttpContext context, WebSocket webSocket)
{
var connection = new Connection(context, webSocket);
Console.WriteLine("Connect: {0}", context.Connection.RemoteIpAddress);
var cancelToken = CancellationToken.None;
var buffer = new byte[1024];
WebSocketReceiveResult received =
await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
while (!webSocket.CloseStatus.HasValue)
{
string text = System.Text.Encoding.UTF8.GetString(buffer, 0, received.Count);
Console.WriteLine("Recd: {0}", text);
try
{
Cmd.Parse(text, connection)?.Run();
}
catch (Exception ex)
{
Console.WriteLine("Unhandled exception: {0}", ex);
}
received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
}
await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, cancelToken);
}
示例2: HandleSocket
private async Task HandleSocket(WebSocket socket)
{
var receiveBuffer = new byte[1024 * 4];
try
{
var result = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
while (!socket.CloseStatus.HasValue)
{
await Task.WhenAll(tasks: SocketsSingleton.Instance.SocketsBag.Where(x => x.State == WebSocketState.Open)
.Select(async x =>
{
await x.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
}));
SocketsSingleton.Instance.SocketsBag = new ConcurrentBag<WebSocket>(SocketsSingleton.Instance.SocketsBag.Where(x => x.State == WebSocketState.Open));
result = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
}
await socket.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.EndpointUnavailable, result.CloseStatusDescription, CancellationToken.None);
}
catch (Exception exception)
{
Console.Write(exception);
}
finally
{
socket?.Dispose();
}
}
示例3: Echo
private async Task Echo(WebSocket webSocket)
{
byte[] buffer = new byte[1024 * 4];
var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!result.CloseStatus.HasValue)
{
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
示例4: EchoWebSocket
private async Task EchoWebSocket(WebSocket webSocket)
{
byte[] buffer = new byte[1024];
WebSocketReceiveResult received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
while (!webSocket.CloseStatus.HasValue)
{
// Echo anything we receive
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, received.Count), received.MessageType, received.EndOfMessage, CancellationToken.None);
received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, CancellationToken.None);
}
示例5: DoWebSocketReceiveSendAsync
private static async Task DoWebSocketReceiveSendAsync(WebSocket receiver, WebSocket sender, CancellationToken ct) {
if (receiver == null || sender == null) {
return;
}
ArraySegment<byte> receiveBuffer = new ArraySegment<byte>(new byte[65335]);
while (receiver.State == WebSocketState.Open && sender.State == WebSocketState.Open) {
if (ct.IsCancellationRequested) {
receiver.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", CancellationToken.None).SilenceException<WebSocketException>().DoNotWait();
sender.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", CancellationToken.None).SilenceException<WebSocketException>().DoNotWait();
return;
}
WebSocketReceiveResult result = await receiver.ReceiveAsync(receiveBuffer, ct);
byte[] data = await receiveBuffer.ToByteArrayAsync(result.Count);
ArraySegment<byte> sendBuffer = new ArraySegment<byte>(data);
await sender.SendAsync(sendBuffer, result.MessageType, result.EndOfMessage, ct);
if (result.MessageType == WebSocketMessageType.Close) {
await receiver.CloseAsync(WebSocketCloseStatus.NormalClosure, "Normal closure", ct);
}
}
}
示例6: ProcessWebSocket
public async Task ProcessWebSocket(HttpContext context, WebSocket webSocket)
{
var connection = new Connection(context, webSocket);
_allConnections.Add(connection);
Console.WriteLine("Connect: {0}", context.Connection.RemoteIpAddress);
var cancelToken = CancellationToken.None;
var buffer = new byte[1024];
WebSocketReceiveResult received =
await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
while (!webSocket.CloseStatus.HasValue)
{
string text = System.Text.Encoding.UTF8.GetString(buffer, 0, received.Count);
Console.WriteLine("Recd: {0}", text);
try
{
var cmd = Cmd.Parse(text, connection);
if (cmd != null) {
// TODO: Remove these dependencies from Cmd
cmd.SpawnDaemon = _spawnDaemon;
cmd.DecayDaemon = _decayDaemon;
cmd.Run();
}
}
catch (Exception ex)
{
Console.WriteLine("Unhandled exception: {0}", ex);
}
received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken);
}
_allConnections.Remove(connection);
await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, cancelToken);
}
示例7: ProcessWebSocketRequestAsync
internal async Task ProcessWebSocketRequestAsync(WebSocket webSocket, CancellationToken disconnectToken, Func<object, Task<WebSocketMessage>> messageRetriever, object state)
{
bool closedReceived = false;
try
{
// first, set primitives and initialize the object
WebSocket = webSocket;
OnOpen();
// dispatch incoming messages
while (!disconnectToken.IsCancellationRequested && !closedReceived)
{
WebSocketMessage incomingMessage = await messageRetriever(state);
switch (incomingMessage.MessageType)
{
case WebSocketMessageType.Binary:
OnMessage((byte[])incomingMessage.Data);
break;
case WebSocketMessageType.Text:
OnMessage((string)incomingMessage.Data);
break;
default:
closedReceived = true;
// If we received an incoming CLOSE message, we'll queue a CLOSE frame to be sent.
// We'll give the queued frame some amount of time to go out on the wire, and if a
// timeout occurs we'll give up and abort the connection.
await Task.WhenAny(CloseAsync(), Task.Delay(_closeTimeout));
break;
}
}
}
catch (OperationCanceledException ex)
{
// ex.CancellationToken never has the token that was actually cancelled
if (!disconnectToken.IsCancellationRequested)
{
Error = ex;
OnError();
}
}
catch (ObjectDisposedException)
{
// If the websocket was disposed while we were reading then noop
}
catch (Exception ex)
{
if (IsFatalException(ex))
{
Error = ex;
OnError();
}
}
try
{
if (WebSocket.State == WebSocketState.Closed ||
WebSocket.State == WebSocketState.Aborted)
{
// No-op if the socket is already closed or aborted
}
else
{
// Close the socket
await WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
}
finally
{
OnClose();
}
}
示例8: ReadSerializedMessage
private async Task<String> ReadSerializedMessage(WebSocket socket)
{
var byteBuffer = new byte[MaxBufferSize];
var arraySegmentBuffer = new ArraySegment<byte>(byteBuffer);
WebSocketReceiveResult result = await socket.ReceiveAsync(arraySegmentBuffer, CancellationToken.None);
string ret = "";
if (result.MessageType == WebSocketMessageType.Close)
{
await
socket.CloseAsync(result.CloseStatus.GetValueOrDefault(), result.CloseStatusDescription,
CancellationToken.None);
}
else
{
int messageSize = 0;
for (messageSize = result.Count; !result.EndOfMessage; messageSize += result.Count)
{
result = await socket.ReceiveAsync(new ArraySegment<byte>(byteBuffer, messageSize, MaxBufferSize - messageSize), CancellationToken.None);
}
if (result.MessageType == WebSocketMessageType.Text)
{
ret = Encoding.UTF8.GetString(byteBuffer, 0, messageSize);
}
}
return ret;
}
示例9: RunWebSocket
private async Task RunWebSocket(IDictionary<string, object> websocketContext)
{
// Try to get the websocket context from the environment
object value;
if (!websocketContext.TryGetValue(typeof(WebSocketContext).FullName, out value))
{
throw new InvalidOperationException("Unable to find web socket context");
}
mWebSocket = ((WebSocketContext)value).WebSocket;
OnOpen();
var buffer = new byte[MaxMessageSize];
do
{
var received = await ReceiveOneMessage(buffer);
if (received.Item1.Count > 0)
OnMessageReceived(received.Item1, received.Item2);
}
while (!mWebSocket.CloseStatus.HasValue);
await mWebSocket.CloseAsync(mWebSocket.CloseStatus.GetValueOrDefault(WebSocketCloseStatus.Empty),
mWebSocket.CloseStatusDescription, mCancellToken.Token);
mCancellToken.Cancel();
OnClose();
}