本文整理汇总了C#中System.Net.HttpListenerContext.AcceptWebSocketAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpListenerContext.AcceptWebSocketAsync方法的具体用法?C# HttpListenerContext.AcceptWebSocketAsync怎么用?C# HttpListenerContext.AcceptWebSocketAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Net.HttpListenerContext
的用法示例。
在下文中一共展示了HttpListenerContext.AcceptWebSocketAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: HandleAsync
public async Task<bool> HandleAsync(HttpListenerContext context)
{
if (context.Request.IsWebSocketRequest)
{
var webSocketContext = await context.AcceptWebSocketAsync(null);
var protocolStream = new DebugStream(new WebSocketStream(webSocketContext.WebSocket));
var protocol = _protocolProvider.GetProtocol(protocolStream);
var delayPerFrame = 1000 / _maximumFramesPerSecond;
using (var screen = _screenProvider.GetScreen())
{
await protocol.StartAsync(screen.GetFrame(Timeout.Infinite));
while (true)
{
var beginTime = DateTime.Now.Ticks;
var screenFrame = screen.GetFrame(0);
if (screenFrame != null && (screenFrame.ModifiedRegions.Length > 0 || screenFrame.MovedRegions.Length > 0))
{
await protocol.UpdateAsync(screenFrame);
}
var elapsedTime = (int) ((DateTime.Now.Ticks - beginTime) / TimeSpan.TicksPerSecond);
if (elapsedTime < delayPerFrame) await Task.Delay(delayPerFrame - elapsedTime);
}
}
}
return false;
}
示例2: HandleRequest
private async void HandleRequest(HttpListenerContext context)
{
Console.WriteLine("New Session.");
var ws = (await context.AcceptWebSocketAsync(subProtocol: null)).WebSocket;
clients.Add(ws);
while (ws.State == WebSocketState.Open)
{
try
{
var buf = new ArraySegment<byte>(new byte[1024]);
var ret = await ws.ReceiveAsync(buf, System.Threading.CancellationToken.None);
if (ret.MessageType == WebSocketMessageType.Close)
{
Console.WriteLine("Session Close.");
break;
}
Console.WriteLine("Got Message.");
}
catch
{
break;
}
}
clients.Remove(ws);
ws.Dispose();
}
示例3: ContextHandler
private async void ContextHandler(HttpListenerContext context)
{
var request = context.Request;
Console.WriteLine("{0} {1} {2}", request.RemoteEndPoint.Address, request.HttpMethod, request.Url);
if (request.IsWebSocketRequest)
webSocketServer.HandleContext(await context.AcceptWebSocketAsync(webSocketServer.Protocol));
else
httpServer.HandleContext(context);
}
示例4: GetResponseAsync
public async Task GetResponseAsync(HttpListenerContext context, string localBaseUrl, string remoteBaseUrl, CancellationToken ct) {
string postUri = null;
if (context.Request.IsWebSocketRequest) {
UriBuilder ub = new UriBuilder(PostUri) { Scheme = "wss" };
postUri = ub.Uri.ToString();
} else {
postUri = PostUri.ToString();
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUri);
request.Method = context.Request.HttpMethod;
request.ServerCertificateValidationCallback += ValidateCertificate;
if (!context.Request.IsWebSocketRequest) {
SetRequestHeaders(request, context.Request.Headers, localBaseUrl, remoteBaseUrl);
}
// Add RTVS headers
request.Headers.Add(CustomHttpHeaders.RTVSRequestedURL, GetRemoteUrl(context.Request.Url, remoteBaseUrl));
if (context.Request.InputStream.CanSeek && context.Request.InputStream.Length > 0) {
using (Stream reqStream = await request.GetRequestStreamAsync()) {
await context.Request.InputStream.CopyAndFlushAsync(reqStream, null, ct);
}
}
HttpWebResponse response = null;
try {
response = (HttpWebResponse)await request.GetResponseAsync();
if (response != null) {
if (context.Request.IsWebSocketRequest && response.StatusCode == HttpStatusCode.SwitchingProtocols) {
Stream respStream = response.GetResponseStream();
string subProtocol = response.Headers[Constants.Headers.SecWebSocketProtocol];
var remoteWebSocket = CommonWebSocket.CreateClientWebSocket(respStream, subProtocol, TimeSpan.FromMinutes(10), receiveBufferSize: 65335, useZeroMask: true);
var websocketContext = await context.AcceptWebSocketAsync(subProtocol, receiveBufferSize: 65335, keepAliveInterval: TimeSpan.FromMinutes(10));
await WebSocketHelper.SendReceiveAsync(websocketContext.WebSocket, remoteWebSocket, ct);
} else {
context.Response.StatusCode = (int)response.StatusCode;
SetResponseHeaders(response, context.Response, localBaseUrl, remoteBaseUrl);
using (Stream respStream = response.GetResponseStream())
using (Stream outStream = context.Response.OutputStream) {
await respStream.CopyAndFlushAsync(outStream, null, ct);
}
response.Close();
}
}
} catch (WebException wex) when (wex.Status == WebExceptionStatus.ProtocolError) {
response = wex.Response as HttpWebResponse;
} finally {
response?.Close();
}
}
示例5: ProcessRequest
private async void ProcessRequest(HttpListenerContext listenerContext)
{
WebSocketContext webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: null);
using (WebSocket webSocket = webSocketContext.WebSocket)
{
Random rand = new Random(1);
while (webSocket.State == WebSocketState.Open)
{
string randomValue = rand.Next(1, 5000).ToString();
ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(randomValue));
await webSocket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
await Task.Delay(new TimeSpan(0, 0, 1));
}
}
}
示例6: Execute
public async void Execute(HttpListenerContext context, EventSocketExecuteResult callback){
WebSocketContext webSocketContext = await context.AcceptWebSocketAsync(null);
_ws = webSocketContext.WebSocket;
for (int i = 0; i != 10; ++i)
{
// await Task.Delay(20);
var time = DateTime.Now.ToLongTimeString();
var buffer = Encoding.UTF8.GetBytes(time);
var segment = new ArraySegment<byte>(buffer);
await _ws.SendAsync(segment, System.Net.WebSockets.WebSocketMessageType.Text,
true, CancellationToken.None);
}
if (callback!=null) {
callback (true);
}
// await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "Done", CancellationToken.None);
}
示例7: StartAccepting
private async void StartAccepting(HttpListenerContext context)
{
do // TODO: add the appropriate try/catch here, utilize User
{
try
{
var socketContext = await context.AcceptWebSocketAsync(null);
if (socketContext != null && !_disposed)
{
var child = new WebSocketTransportSource(socketContext.WebSocket);
child.Received += OnChildReceived;
_cache[socketContext.WebSocket] = child;
}
}
catch (IndexOutOfRangeException)
{
// no idea what is causing this
break;
}
} while (_listener.IsListening && !_disposed);
}
示例8: ProcessWebSocketRequest
/// <summary>
/// Processes the web socket request.
/// </summary>
/// <param name="ctx">The CTX.</param>
/// <returns>Task.</returns>
private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
{
#if !__MonoCS__
try
{
var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);
if (WebSocketHandler != null)
{
WebSocketHandler(new WebSocketConnectEventArgs
{
WebSocket = new NativeWebSocket(webSocketContext.WebSocket, _logger),
Endpoint = ctx.Request.RemoteEndPoint.ToString()
});
}
}
catch (Exception ex)
{
_logger.ErrorException("AcceptWebSocketAsync error", ex);
ctx.Response.StatusCode = 500;
ctx.Response.Close();
}
#endif
}
示例9: HandleWebSocketRequest
private static async void HandleWebSocketRequest(HttpListenerContext hc)
{
HttpListenerWebSocketContext connectionCtx;
try
{
connectionCtx = await hc.AcceptWebSocketAsync(null);
var webSocketInfo = new WebSocketInfo(connectionCtx.WebSocket);
_sockets[webSocketInfo.Socket] = webSocketInfo;
CommandListener(webSocketInfo);
}
catch (Exception ex)
{
Trace.WriteLine(nameof(MaintFace) + " Error: " + nameof(HandleWebSocketRequest) + ": " + ex.Message);
return;
}
}
示例10: HandleListenerContextAsync
async Task HandleListenerContextAsync(HttpListenerContext context)
{
WebSocket webSocket = null;
try
{
var wsContext = await context.AcceptWebSocketAsync(WebSocketTransport.WebSocketSubProtocol);
var wsTransport = new WebSocketTransport(wsContext.WebSocket);
await this.listener.HandleTransportAsync(wsTransport);
}
catch(Exception exception)
{
Trace.WriteLine(TraceLevel.Error, exception.ToString());
if (webSocket != null)
{
webSocket.Abort();
}
}
}
示例11: ProcessRequest
private async void ProcessRequest(HttpListenerContext httpListenerContext)
{
WebSocketContext webSocketContext = null;
try
{
webSocketContext = await httpListenerContext.AcceptWebSocketAsync(subProtocol: null);
string ipAddress = httpListenerContext.Request.RemoteEndPoint.Address.ToString();
Console.WriteLine(String.Format("Connected: IPAddress {0}", ipAddress));
if (onConnect != null && httpListenerContext.Request.Headers.AllKeys.Contains("Sec-WebSocket-Key"))
onConnect(httpListenerContext.Request.Headers["Sec-WebSocket-Key"]);
}
catch (Exception ex)
{
httpListenerContext.Response.StatusCode = 500;
httpListenerContext.Response.Close();
if (onError != null)
onError(String.Empty, ex);
Console.WriteLine(String.Format("Exception: {0}", ex));
return;
}
WebSocket webSocket = webSocketContext.WebSocket;
String requestKey = httpListenerContext.Request.Headers["Sec-WebSocket-Key"];
webSocketDictionary.Add(requestKey, webSocket);
try
{
byte[] receiveBuffer = new byte[1024];
while(webSocket.State == WebSocketState.Open)
{
WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), System.Threading.CancellationToken.None);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", System.Threading.CancellationToken.None);
webSocketDictionary.Remove(requestKey);
}
else
{
string message = Util.GetString(receiveBuffer, receiveResult.Count);
if (onMessage != null)
onMessage(requestKey, message);
await webSocketDictionary.SendBroadcastMessage(message);
receiveBuffer = new byte[1024];
}
}
}
catch (Exception ex)
{
if (onError != null)
onError(requestKey, ex);
Console.WriteLine(String.Format("Exception: {0}", ex));
}
finally
{
if (webSocket != null)
webSocket.Dispose();
}
}
示例12: ProcessRequest
/// <summary>
/// WebSocket接続毎の処理
/// </summary>
/// <param name="context"></param>
async void ProcessRequest(HttpListenerContext context)
{
Console.WriteLine("{0}:New Session:{1}", DateTime.Now.ToString(), context.Request.RemoteEndPoint.Address.ToString());
/// WebSocketの接続完了を待機してWebSocketオブジェクトを取得する
var ws = (await (context.AcceptWebSocketAsync(null))).WebSocket;
/// 新規クライアントを追加
_clients.Add(ws);
/// WebSocketの送受信ループ
while (ws.State == WebSocketState.Open)
{
try
{
var buff = new ArraySegment<byte>(new byte[1024]);
/// 受信待機
var ret = await ws.ReceiveAsync(buff, CancellationToken.None);
/// テキスト
if (ret.MessageType == WebSocketMessageType.Text)
{
Console.WriteLine("{0}:String Received:{1}", DateTime.Now.ToString(), context.Request.RemoteEndPoint.Address.ToString());
string msgjson = Encoding.UTF8.GetString(buff.Take(ret.Count).ToArray());
Console.WriteLine("Message={0}", msgjson);
Message msg = MessageParser.Parse(msgjson);
if (msg.GetType() == typeof(JoinRoom))
{
HashSet<WebSocket> room = _rooms[ws.GetHashCode().ToString()];
room.Add(ws);
_rooms[ws.GetHashCode().ToString()] = room;
foreach (KeyValuePair<string, HashSet<WebSocket>> val in _rooms)
{
if (val.Key == ws.GetHashCode().ToString()) continue;
else
{
val.Value.Contains(ws);
}
}
}
/// 各クライアントへ配信
Parallel.ForEach(_clients, p => p.SendAsync(new ArraySegment<byte>(buff.Take(ret.Count).ToArray()), WebSocketMessageType.Text, true, CancellationToken.None));
}
else if (ret.MessageType == WebSocketMessageType.Close)
{
Console.WriteLine("{0}:Session Close:{1}", DateTime.Now.ToString(), context.Request.RemoteEndPoint.Address.ToString());
break;
}
}
catch
{
/// 例外 クライアントが異常終了しやがった
Console.WriteLine("{0}:Session Abort:{1}", DateTime.Now.ToString(), context.Request.RemoteEndPoint.Address.ToString());
break;
}
}
/// クライアントを除外する
_clients.Remove(ws);
ws.Dispose();
}
示例13: ProcessRequest
//### Accepting WebSocket connections
// Calling `AcceptWebSocketAsync` on the `HttpListenerContext` will accept the WebSocket connection, sending the required 101 response to the client
// and return an instance of `WebSocketContext`. This class captures relevant information available at the time of the request and is a read-only
// type - you cannot perform any actual IO operations such as sending or receiving using the `WebSocketContext`. These operations can be
// performed by accessing the `System.Net.WebSocket` instance via the `WebSocketContext.WebSocket` property.
private async void ProcessRequest(HttpListenerContext listenerContext)
{
WebSocketContext webSocketContext = null;
try
{
// When calling `AcceptWebSocketAsync` the negotiated subprotocol must be specified. This sample assumes that no subprotocol
// was requested.
webSocketContext = await listenerContext.AcceptWebSocketAsync(subProtocol: null);
Interlocked.Increment(ref count);
Console.WriteLine("Processed: {0}", count);
}
catch(Exception e)
{
// The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500.
listenerContext.Response.StatusCode = 500;
listenerContext.Response.Close();
Console.WriteLine("Exception: {0}", e);
return;
}
WebSocket webSocket = webSocketContext.WebSocket;
try
{
//### Receiving
// Define a receive buffer to hold data received on the WebSocket connection. The buffer will be reused as we only need to hold on to the data
// long enough to send it back to the sender.
byte[] receiveBuffer = new byte[1024];
// While the WebSocket connection remains open run a simple loop that receives data and sends it back.
while (webSocket.State == WebSocketState.Open)
{
// The first step is to begin a receive operation on the WebSocket. `ReceiveAsync` takes two parameters:
//
// * An `ArraySegment` to write the received data to.
// * A cancellation token. In this example we are not using any timeouts so we use `CancellationToken.None`.
//
// `ReceiveAsync` returns a `Task<WebSocketReceiveResult>`. The `WebSocketReceiveResult` provides information on the receive operation that was just
// completed, such as:
//
// * `WebSocketReceiveResult.MessageType` - What type of data was received and written to the provided buffer. Was it binary, utf8, or a close message?
// * `WebSocketReceiveResult.Count` - How many bytes were read?
// * `WebSocketReceiveResult.EndOfMessage` - Have we finished reading the data for this message or is there more coming?
WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
// The WebSocket protocol defines a close handshake that allows a party to send a close frame when they wish to gracefully shut down the connection.
// The party on the other end can complete the close handshake by sending back a close frame.
//
// If we received a close frame then lets participate in the handshake by sending a close frame back. This is achieved by calling `CloseAsync`.
// `CloseAsync` will also terminate the underlying TCP connection once the close handshake is complete.
//
// The WebSocket protocol defines different status codes that can be sent as part of a close frame and also allows a close message to be sent.
// If we are just responding to the client's request to close we can just use `WebSocketCloseStatus.NormalClosure` and omit the close message.
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
// This echo server can't handle text frames so if we receive any we close the connection with an appropriate status code and message.
else if (receiveResult.MessageType == WebSocketMessageType.Text)
{
await webSocket.CloseAsync(WebSocketCloseStatus.InvalidMessageType, "Cannot accept text frame", CancellationToken.None);
}
// Otherwise we must have received binary data. Send it back by calling `SendAsync`. Note the use of the `EndOfMessage` flag on the receive result. This
// means that if this echo server is sent one continuous stream of binary data (with EndOfMessage always false) it will just stream back the same thing.
// If binary messages are received then the same binary messages are sent back.
else
{
await webSocket.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, receiveResult.Count), WebSocketMessageType.Binary, receiveResult.EndOfMessage, CancellationToken.None);
}
// The echo operation is complete. The loop will resume and `ReceiveAsync` is called again to wait for the next data frame.
}
}
catch(Exception e)
{
// Just log any exceptions to the console. Pretty much any exception that occurs when calling `SendAsync`/`ReceiveAsync`/`CloseAsync` is unrecoverable in that it will abort the connection and leave the `WebSocket` instance in an unusable state.
Console.WriteLine("Exception: {0}", e);
}
finally
{
// Clean up by disposing the WebSocket once it is closed/aborted.
if (webSocket != null)
webSocket.Dispose();
}
}
示例14: Handshake
private async Task<WebSocket> Handshake(HttpListenerContext ctx) {
WebSocketContext webSocketContext = null;
try {
// When calling `AcceptWebSocketAsync` the negotiated subprotocol must be specified. This sample assumes that no subprotocol
// was requested.
webSocketContext = await ctx.AcceptWebSocketAsync(subProtocol: null);
LogFacade.Instance.LogInfo("Accepted web socket connection");
}
catch (Exception e) {
// The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500.
ctx.Response.StatusCode = 500;
ctx.Response.Close();
}
return webSocketContext.IsNull() ? null : webSocketContext.WebSocket;
}
示例15: ProcessConnectionAsync
private async Task<bool> ProcessConnectionAsync(
CancellationToken cancellationToken,
HttpListenerContext httpContext)
{
Logger.Debug("ProcessConnectionAsync");
WebSocketContext webSocketContext = null;
try
{
webSocketContext = await httpContext.AcceptWebSocketAsync(null);
}
catch (Exception ex)
{
Logger.Error(ex, "AcceptWebSocketAsync");
// The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500.
httpContext.Response.StatusCode = 500;
httpContext.Response.Close();
return false;
}
WebSocket webSocket = webSocketContext.WebSocket;
MemoryStream ms = new MemoryStream();
try
{
IWebSocketConnectionHandler handler = this.createConnectionHandler();
byte[] receiveBuffer = null;
// While the WebSocket connection remains open run a simple loop that receives data and sends it back.
while (webSocket.State == WebSocketState.Open)
{
try
{
if (receiveBuffer == null)
{
receiveBuffer = new byte[MaxBufferSize];
}
WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), cancellationToken);
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
Logger.Debug("ProcessConnectionAsync: closing websocket");
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", cancellationToken);
continue;
}
if (receiveResult.EndOfMessage)
{
await ms.WriteAsync(receiveBuffer, 0, receiveResult.Count, cancellationToken);
receiveBuffer = ms.ToArray();
ms.Dispose();
ms = new MemoryStream();
}
else
{
await ms.WriteAsync(receiveBuffer, 0, receiveResult.Count, cancellationToken);
continue;
}
byte[] wsresponse = null;
try
{
// dispatch to App provided function with requested payload
wsresponse = await handler.ProcessWsMessageAsync(receiveBuffer, cancellationToken);
}
catch (Exception ex)
{
// catch any error in the appAction and notify the client
wsresponse = await new ProtobufWsSerializer().SerializeAsync(
new WsResponseMessage
{
Result = WsResult.Error,
Value = Encoding.UTF8.GetBytes(ex.Message)
});
}
// Send Result back to client
await webSocket.SendAsync(
new ArraySegment<byte>(wsresponse),
WebSocketMessageType.Binary,
true,
cancellationToken);
}
catch (WebSocketException ex)
{
Logger.Error(ex, "ProcessConnectionAsync: WebSocketException={0}", webSocket.State);
}
}
return true;
}
catch (Exception ex)
{
Logger.Error(ex, "ProcessConnectionAsync");
throw;
}
}
开发者ID:Azure-Samples,项目名称:service-fabric-dotnet-data-streaming-websockets,代码行数:98,代码来源:WebSocketListener.cs