琼中黎族苗族自治县网站建设_网站建设公司_图标设计_seo优化
2025/12/29 11:23:47 网站建设 项目流程

一、NuGet 包管理器中下载相关包

安装 SuperSocket.WebSocket.Server 包
image

二、启动SocketServer服务

注册启动WebSocket Server 服务方法
`
///


/// WebSocket服务器实例
///

private IHost? _webSocketServer;

///


/// 启动 WebSocket Server 服务
///

/// 监听端口
/// 监听IP地址
/// 取消令牌
/// 异步任务
public async Task WebSocketServerAsync(int port, IPAddress ip, CancellationToken cancellationToken = default)
{
try
{
_webSocketServer = WebSocketHostBuilder.Create()
.UseWebSocketMessageHandler(
async (session, message) => await HandleWebSocketMessageAsync(session, message.Message)
)
.ConfigureAppConfiguration((hostContext, configApp) =>
{
var config = new Dictionary<string, string>
{
["serverOptions:listeners:0:ip"] = ip.ToString(),
["serverOptions:listeners:0:port"] = port.ToString()
};
configApp.AddInMemoryCollection(config);
})
.Build();

    // 启动WebSocket服务器await _webSocketServer.RunAsync(cancellationToken);
}
catch (Exception ex)
{Console.WriteLine($"WebSocket服务器启动失败: {ex.Message}");
}

}
`

三、消息处理,通过反射加载对应请求处理方法

消息处理,通过反射加载对应请求处理方法

`
///


/// 方法缓存,用于存储反射获取的Socket相关方法
///

private Dictionary<string, MethodInfo> _webSocketMethodCache = new();

///


/// 存储所有连接的WebSocket会话
///

private readonly ConcurrentDictionary<string, WebSocketSession> _connectedSessions = new();

///


/// 处理 WebSocket 消息
///

/// WebSocket会话
/// WebSocket消息
/// 异步任务
private async Task HandleWebSocketMessageAsync(WebSocketSession session, string message)
{
// 确保会话已添加到连接列表
if (_connectedSessions.TryAdd(session.SessionID ?? Guid.NewGuid().ToString(), session))
{
Console.WriteLine($"新会话已连接: {session.SessionID}");
}
// 处理收到的消息
await OnWebSocketMessageAsync(session, message);
}

///


/// 处理接收到的 WebSocket 消息
///

/// WebSocket会话
/// WebSocket消息
/// 异步任务
private async Task OnWebSocketMessageAsync(WebSocketSession session, string message)
{
try
{
// Console.WriteLine($"收到消息: {message}");
JObject messageObject;
try
{
messageObject = JObject.Parse(message);
// TODO: 检查是否有topic属性
if (messageObject["topic"] != null)
{
// 根据不同的topic来处理不同的消息
string topic = messageObject["topic"].ToString();

            // TODO: 先检查topic和op对应的方法是否缓存MethodInfo memberInfo = null;if (_webSocketMethodCache.TryGetValue(topic, out memberInfo)){// 当前的方法已经在缓存中,直接调用memberInfo.Invoke(this, new object[] { session, message });return;}// TODO: 没有找到对应的方法,则进行反射var methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);foreach (var method in methods){var attributes = method.GetCustomAttributes(typeof(WebSocketMessageAttribute), false);if (attributes.Length > 0){var attribute = attributes[0] as WebSocketMessageAttribute;if (attribute.Topic == topic){// TODO: 把method进行缓存,免得每次都需要反射_webSocketMethodCache.Add(topic, method);// TODO: 把method添加到Dictionary中,key是topic,value是methodmethod.Invoke(this, new object[] { session, message });}}}}}catch (Exception ex){Console.WriteLine($"检查是否有topic属性,{ex.Message}");}}
catch (Exception ex)
{Console.WriteLine($"处理WebSocket消息时出错: {ex.Message}");
}

}

`

`
///


/// WebSocket消息属性
///

public class WebSocketMessageAttribute : Attribute
{
public string Topic { get; }

 public WebSocketMessageAttribute(string topic){Topic = topic;}

}
`

/// <summary> /// 获取Joint状态,则返回joint值 /joint_states /// </summary> /// <param name="session"></param> /// <param name="message"></param> /// <returns></returns> [WebSocketMessage("/joint_states")] private async Task JointStatesAsync(WebSocketSession session, string message) { try { // TODO: 获取并解析消息文本 Console.WriteLine(message); } catch (Exception ex) { Console.WriteLine($"获取/joint_states报错,{ex.Message}"); } }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询