本文整理汇总了C#中System.Net.WebSockets.WebSocket类的典型用法代码示例。如果您正苦于以下问题:C# WebSocket类的具体用法?C# WebSocket怎么用?C# WebSocket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WebSocket类属于System.Net.WebSockets命名空间,在下文中一共展示了WebSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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: keyboardHandler
private void keyboardHandler(WebSocket ws)
{
byte[] buffer = new byte[4096 * 4096];
var task = ws.ReceiveAsync(new ArraySegment<byte>(buffer), System.Threading.CancellationToken.None).ContinueWith((ReceiveResult) =>
{
string s = System.Text.Encoding.ASCII.GetString(buffer);
s = s.TrimEnd('\0', ' ');
foreach (string keyboardCmd in s.Split(' ', '\0'))
{
string cmd = keyboardCmd.ToLower().Trim();
if (keyboardCmd.StartsWith("up/") && keyboardCmd.Length > "up/".Length)
{
Keyboard.KeyUp(int.Parse(keyboardCmd.Substring("up/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
}
if (keyboardCmd.StartsWith("down/") && keyboardCmd.Length > "down/".Length)
{
Keyboard.KeyDown(int.Parse(keyboardCmd.Substring("down/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
}
if (keyboardCmd.StartsWith("tap/") && keyboardCmd.Length > "tap/".Length)
{
Keyboard.KeyTap(int.Parse(keyboardCmd.Substring("tap/".Length), System.Globalization.NumberStyles.AllowHexSpecifier));
}
}
keyboardHandler(ws);
});
}
示例3: DashboardSocketHandler
public DashboardSocketHandler(WebSocket socket)
{
Socket = socket;
MasterController.Instance.Listener.Status.Updated += ListenerStatusUpdated;
MasterController.Instance.Transmitter.Status.Updated += TransmitterStatusUpdated;
Venue.Status.Updated += Status_Updated;
}
示例4: TestChatHanlder_OnReceive
private void TestChatHanlder_OnReceive(WebSocket Socket, WebSocketMessageType Type, byte[] ReceiveMessage)
{
//並行廣播給所有使用者,也可以轉發給指定使用者
Parallel.ForEach(WebSocketList, async socket => {
await socket.SendAsync(new ArraySegment<byte>(ReceiveMessage), Type, true, CancellationToken.None);
});
}
示例5: SocketServer
public SocketServer()
{
var websocket = new WebSocket();
_tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 56837);//8095
_dictionary = new ConcurrentDictionary<string, SocketWrapper>();
_connections = new List<SocketWrapper>();
}
示例6: ReceiveAsync
static async Task<Message> ReceiveAsync(WebSocket ws)
{
byte[] buffer = new byte[4096];
var seg = new ArraySegment<byte>(buffer);
var result = await ws.ReceiveAsync(seg, CancellationToken.None);
return Message.Deserialize(new ArraySegment<byte>(buffer, 0, result.Count));
}
示例7: SACNTransmitterLive
public SACNTransmitterLive(WebSocket socket)
{
Socket = socket;
var Transmitter = MasterController.Instance.Transmitter as SACNTransmitter;
UniverseID = 1;
Transmitter.OnTransmit += Transmitter_OnTransmit;
}
示例8: 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();
}
}
示例9: SendMessage
private static async Task SendMessage(WebSocket webSocket, string msg, bool endOfMessage)
{
logger.LogVerbose("SendMessage = {0}", msg);
var msgBytes = Encoding.UTF8.GetBytes(msg);
await webSocket.SendAsync(new ArraySegment<byte>(msgBytes, 0, msgBytes.Length), WebSocketMessageType.Text, endOfMessage, CancellationToken.None);
}
示例10: Connection
public Connection(HttpContext context, WebSocket socket)
{
Id = Guid.NewGuid();
Context = context;
Socket = socket;
AccessLevel = AccessLevel.Guest;
}
示例11: ReadMessageAsync
public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, byte[] buffer, int maxMessageSize)
{
ArraySegment<byte> arraySegment = new ArraySegment<byte>(buffer);
WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
// special-case close messages since they might not have the EOF flag set
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
return new WebSocketMessage(null, WebSocketMessageType.Close);
}
if (receiveResult.EndOfMessage)
{
// we anticipate that single-fragment messages will be common, so we optimize for them
switch (receiveResult.MessageType)
{
case WebSocketMessageType.Binary:
return new WebSocketMessage(BufferSliceToByteArray(buffer, receiveResult.Count), WebSocketMessageType.Binary);
case WebSocketMessageType.Text:
return new WebSocketMessage(BufferSliceToString(buffer, receiveResult.Count), WebSocketMessageType.Text);
default:
throw new Exception("This code path should never be hit.");
}
}
else
{
// for multi-fragment messages, we need to coalesce
ByteBuffer bytebuffer = new ByteBuffer(maxMessageSize);
bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
WebSocketMessageType originalMessageType = receiveResult.MessageType;
while (true)
{
// loop until an error occurs or we see EOF
receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
if (receiveResult.MessageType != originalMessageType)
{
throw new InvalidOperationException("Incorrect message type");
}
bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count));
if (receiveResult.EndOfMessage)
{
switch (receiveResult.MessageType)
{
case WebSocketMessageType.Binary:
return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary);
case WebSocketMessageType.Text:
return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text);
default:
throw new Exception("This code path should never be hit.");
}
}
}
}
}
示例12: EchoAsync
public async Task EchoAsync(WebSocket webSocket)
{
var buffer = new ArraySegment<byte>(new byte[8192]);
for (; ;)
{
var result = await webSocket.ReceiveAsync(
buffer,
CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Close)
{
return;
}
else if (result.MessageType == WebSocketMessageType.Text)
{
Console.WriteLine("{0}", System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count));
}
await webSocket.SendAsync(
new ArraySegment<byte>(buffer.Array, 0, result.Count),
result.MessageType,
result.EndOfMessage,
CancellationToken.None);
}
}
示例13: 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;
}
示例14: WebsocketSendAsync
public WebsocketSendAsync(WebSocket webSocket, CompletionQueue completion_queue)
{
if (null == webSocket) throw new ArgumentException();
this.webSocket = webSocket;
if (null == completion_queue) throw new ArgumentException();
this.completion_queue = completion_queue;
}
示例15: ProcessRequestAsync
public override async Task ProcessRequestAsync(HttpContext httpContext)
{
await Task.Run(() =>
{
if (httpContext.IsWebSocketRequest)
{
httpContext.AcceptWebSocketRequest(async delegate(AspNetWebSocketContext context)
{
this.Socket = context.WebSocket;
while (this.Socket != null || this.Socket.State != WebSocketState.Closed)
{
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
WebSocketReceiveResult receiveResult = await this.Socket.ReceiveAsync(buffer, CancellationToken.None);
try
{
switch (receiveResult.MessageType)
{
case WebSocketMessageType.Text:
string message = Encoding.UTF8.GetString(buffer.Array, 0, receiveResult.Count);
this.OnMessageReceived(message);
break;
case WebSocketMessageType.Binary:
this.OnMessageReceived(buffer.Array);
break;
case WebSocketMessageType.Close:
this.OnClosing(true, receiveResult.CloseStatusDescription);
break;
}
switch (this.Socket.State)
{
case WebSocketState.Connecting:
this.OnConnecting();
break;
case WebSocketState.Open:
this.OnOpen();
break;
case WebSocketState.CloseSent:
this.OnClosing(false, string.Empty);
break;
case WebSocketState.CloseReceived:
this.OnClosing(true, string.Empty);
break;
case WebSocketState.Closed:
this.OnClosed();
break;
}
}
catch (Exception ex)
{
this.OnError(ex);
}
}
});
}
});
}