add subprotocols
This commit is contained in:
parent
33d2c28712
commit
8b29044671
2 changed files with 31 additions and 3 deletions
|
@ -227,7 +227,7 @@ public sealed class HttpRequest
|
|||
/// <summary>
|
||||
/// Sends a "switching protocol" header for a websocket.
|
||||
/// </summary>
|
||||
public async Task<Websocket?> UpgradeToWebsocket()
|
||||
public async Task<Websocket?> UpgradeToWebsocket(params string[]? protocols)
|
||||
{
|
||||
if (!Headers.TryGetValue("Sec-WebSocket-Key", out string? wsKey))
|
||||
{
|
||||
|
@ -241,15 +241,37 @@ public sealed class HttpRequest
|
|||
|
||||
string acceptKey = Convert.ToBase64String(SHA1.HashData(Encoding.ASCII.GetBytes(wsKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")));
|
||||
|
||||
string? chosenProtocol = null;
|
||||
string? requestedProtocols = Headers["Sec-WebSocket-Protocol"];
|
||||
if (requestedProtocols != null && protocols != null && protocols.Length > 0)
|
||||
{
|
||||
foreach (string supported in protocols)
|
||||
{
|
||||
foreach (string requested in requestedProtocols.ToLower().Split(',', StringSplitOptions.TrimEntries))
|
||||
{
|
||||
if (requested == supported)
|
||||
{
|
||||
chosenProtocol = supported;
|
||||
goto a;
|
||||
}
|
||||
}
|
||||
}
|
||||
await Write(new BadRequest("Unsupported websocket subprotocol"));
|
||||
return null;
|
||||
}
|
||||
|
||||
a:
|
||||
await WriteStatus(101, "Switching Protocols");
|
||||
await WriteHeader("Upgrade", "websocket");
|
||||
await WriteHeader("Connection", "Upgrade");
|
||||
await WriteHeader("Sec-WebSocket-Accept", acceptKey);
|
||||
await WriteHeader("Access-Control-Allow-Origin", "*");
|
||||
if (chosenProtocol != null)
|
||||
await WriteHeader("Sec-WebSocket-Protocol", chosenProtocol);
|
||||
await WriteLine();
|
||||
await Flush();
|
||||
|
||||
return new Websocket(this);
|
||||
return new Websocket(this, chosenProtocol);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -14,11 +14,17 @@ public sealed class Websocket
|
|||
/// </summary>
|
||||
public readonly HttpRequest Request;
|
||||
|
||||
/// <summary>
|
||||
/// The chosen sub-protocol requested by the client and supported by the server.
|
||||
/// </summary>
|
||||
public readonly string? SubProtocol;
|
||||
|
||||
readonly List<byte> finalPayload = new List<byte>();
|
||||
|
||||
internal Websocket(HttpRequest client)
|
||||
internal Websocket(HttpRequest client, string? subProtocol)
|
||||
{
|
||||
Request = client;
|
||||
SubProtocol = subProtocol;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
Loading…
Reference in a new issue