refactor: Add handy WebsocketExtensions
* IsSocketStateOpen * IsClosedProperly
This commit is contained in:
1 parent
de7c94014e
commit
003b0a3fa0
7 files changed
+65
-19
No files matched your search
@@ -41,6 +41,14 @@ namespace BCG {
|
||||
|
||||
#endregion
|
||||
|
||||
public PubSubRoute Clone() =>
|
||||
new() {
|
||||
server_address = server_address,
|
||||
tag_reg_exp = tag_reg_exp,
|
||||
name = name,
|
||||
};
|
||||
|
||||
|
||||
public override bool Equals(object obj) {
|
||||
if (!(obj is PubSubRoute) || obj == null)
|
||||
return false;
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace Spark.Core.Protobuf {
|
||||
|
||||
using System;
|
||||
|
||||
public interface IProtobuf<T> : ICloneable<T>, IEquatable<T> {
|
||||
public interface IProtobuf<T> : ICloneable<T>, IEquatable<T> where T : notnull {
|
||||
object ICloneable.Clone() =>
|
||||
Clone() ?? throw new InvalidOperationException();
|
||||
}
|
||||
|
||||
@@ -5,9 +5,10 @@ using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Numerics;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace mbts.utils {
|
||||
static class ExceptionAssert {
|
||||
public static class ExceptionAssert {
|
||||
public static T of_type<T>(object obj, string name = null) =>
|
||||
obj is T ? (T)obj : throw new ArgumentException($"Expected {typeof(T)}, actually {(obj?.GetType()?.ToString() ?? "null")}.", name);
|
||||
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
namespace bts {
|
||||
using System;
|
||||
|
||||
public interface ICloneable<T> : ICloneable {
|
||||
public interface ICloneable<T> : ICloneable where T : notnull {
|
||||
new T Clone();
|
||||
|
||||
object ICloneable.Clone() =>
|
||||
Clone();
|
||||
}
|
||||
}
|
||||
@@ -110,9 +110,6 @@ namespace bts.websocket_core {
|
||||
/// can access the store but not change anything in it,
|
||||
/// </summary>
|
||||
class WebSocketHandler {
|
||||
|
||||
private static bool IsSocketStateOpen(WebSocket? ws) => ws != null && ws.State != WebSocketState.Closed && ws.State != WebSocketState.Aborted && ws.State != WebSocketState.None;
|
||||
private static bool IsClosedProperly(WebSocket ws) => ws.CloseStatus == WebSocketCloseStatus.NormalClosure;
|
||||
/// <summary>
|
||||
/// GetConnectedWebSocket attempts to retrieve a connected WebSocket from the WebSocketConnectionStore using the provided client ID.
|
||||
/// If the socket is not found or is not in an open state, it logs an error message and calls the HandleDisconnection method on the
|
||||
@@ -122,16 +119,14 @@ namespace bts.websocket_core {
|
||||
/// <param name="error_message">The error message to log if the WebSocket is not found or not open.</param>
|
||||
/// <returns>The connected WebSocket or null if it was not found or not open.</returns>
|
||||
private WebSocket? GetConnectedWebSocket(WebsocketClientID id, string error_message) {
|
||||
LoggerContext logger = new(Log.Gen, error_message, "");
|
||||
var socket = Connections.GetSocket(id);
|
||||
if (IsSocketStateOpen(socket)) {
|
||||
if (socket?.IsOpen() ?? false) {
|
||||
return socket;
|
||||
}
|
||||
if (socket != null) {
|
||||
logger.warn(" failed as Socket closed");
|
||||
} else {
|
||||
logger.warn(" failed as could not find socket in dictionary");
|
||||
}
|
||||
Log.Gen.warn(
|
||||
$"GetConnectedWebsocket failed: {(socket is null ?
|
||||
"could not find socket in dictionary" :
|
||||
"socket is closed")}");
|
||||
gtwy.HandleDisconnection(id, error_message);
|
||||
return null;
|
||||
}
|
||||
@@ -145,10 +140,13 @@ namespace bts.websocket_core {
|
||||
public bool ShouldDisconnect(WebsocketClientID id, Connection conn, string error_message) {
|
||||
LoggerContext logger = new(Log.Gen, error_message, "");
|
||||
var socket = conn.Ws;
|
||||
if (IsSocketStateOpen(socket)) {
|
||||
if (socket is null) {
|
||||
return false;
|
||||
}
|
||||
if (socket.IsOpen()) {
|
||||
return true;
|
||||
}
|
||||
if (!IsClosedProperly(socket)) {
|
||||
if (!socket.IsClosedProperly()) {
|
||||
logger.info(" closed improperly by other thread");
|
||||
gtwy.NotifyDisconnection(id);
|
||||
}
|
||||
@@ -215,7 +213,7 @@ namespace bts.websocket_core {
|
||||
if (socket == null || que == null) {
|
||||
return;
|
||||
}
|
||||
while (IsSocketStateOpen(socket)) {
|
||||
while (socket.IsOpen()) {
|
||||
// Try to dequeue a message from the queue
|
||||
if (!que.TryDequeue(out var message)) {
|
||||
// If the queue is empty, wait for 100 milliseconds before trying again
|
||||
@@ -274,7 +272,7 @@ namespace bts.websocket_core {
|
||||
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[256]);
|
||||
WebSocketReceiveResult result;
|
||||
string request = "";
|
||||
while (IsSocketStateOpen(socket)) {
|
||||
while (socket.IsOpen()) {
|
||||
// Receive the message
|
||||
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
|
||||
// If the message is a close request, handle the disconnection and return
|
||||
@@ -432,7 +430,18 @@ namespace bts.websocket_core {
|
||||
|
||||
_server_params = server_params;
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
builder.WebHost.UseUrls(_server_params.Uri());
|
||||
|
||||
var localServerParams = _server_params.Clone();
|
||||
localServerParams.Scheme = "http";
|
||||
var localUri = localServerParams.Uri();
|
||||
builder.WebHost.UseUrls(localUri);
|
||||
|
||||
var publicServerParams = _server_params.Clone();
|
||||
publicServerParams.Scheme = "https";
|
||||
publicServerParams.Host = "192.168.50.94";
|
||||
var publicUri = publicServerParams.Uri();
|
||||
builder.WebHost.UseUrls(publicUri);
|
||||
|
||||
// var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
|
||||
builder.Services.AddLogging(builder => {
|
||||
builder.AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Warning)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace bts.websocket_core;
|
||||
|
||||
using System.Net.WebSockets;
|
||||
|
||||
public static class WebsocketExtensions {
|
||||
public static bool IsOpen(this WebSocket ws) =>
|
||||
ws.State switch {
|
||||
WebSocketState.None or WebSocketState.Closed or WebSocketState.Aborted => false,
|
||||
_ => true
|
||||
};
|
||||
|
||||
public static bool IsClosedProperly(this WebSocket ws) =>
|
||||
ws.CloseStatus == WebSocketCloseStatus.NormalClosure;
|
||||
}
|
||||
@@ -1,9 +1,20 @@
|
||||
namespace Bts.Websocket;
|
||||
|
||||
public class WebsocketServerConfig {
|
||||
using bts;
|
||||
|
||||
public class WebsocketServerConfig : ICloneable<WebsocketServerConfig> {
|
||||
public string? Host { get; set; }
|
||||
public string? Port { get; set; }
|
||||
public string? Scheme { get; set; }
|
||||
public string? DefaultEndPoint { get; set; }
|
||||
public double KeepAliveIntervalSecs { get; set; }
|
||||
|
||||
public WebsocketServerConfig Clone() =>
|
||||
new() {
|
||||
Host = Host,
|
||||
Port = Port,
|
||||
Scheme = Scheme,
|
||||
DefaultEndPoint = DefaultEndPoint,
|
||||
KeepAliveIntervalSecs = KeepAliveIntervalSecs,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user