|
|
@ -11,6 +11,7 @@ using CellularManagement.WebSocket.Extensions; |
|
|
|
using CellularManagement.WebSocket.Services; |
|
|
|
using CellularManagement.WebSocket.Connection; |
|
|
|
using System.Text.Json; |
|
|
|
using Microsoft.Extensions.Logging; |
|
|
|
|
|
|
|
// 创建 Web 应用程序构建器
|
|
|
|
var builder = WebApplication.CreateBuilder(args); |
|
|
@ -107,12 +108,16 @@ app.MapControllers(); |
|
|
|
|
|
|
|
// 获取 WebSocket 消息服务实例
|
|
|
|
var messageService = app.Services.GetRequiredService<WebSocketMessageService>(); |
|
|
|
var _logger = app.Services.GetRequiredService<ILogger<Program>>(); |
|
|
|
|
|
|
|
// 注册消息处理器示例
|
|
|
|
messageService.RegisterMessageHandler("chat", async (message) => |
|
|
|
{ |
|
|
|
// 处理聊天消息
|
|
|
|
_logger.LogInformation("开始处理聊天消息,连接ID:{ConnectionId}", message.ConnectionId); |
|
|
|
_logger.LogDebug("原始消息数据:{Data}", System.Text.Encoding.UTF8.GetString(message.Data)); |
|
|
|
|
|
|
|
await Task.Delay(100); // 模拟异步处理
|
|
|
|
|
|
|
|
var response = new WebSocketMessage |
|
|
|
{ |
|
|
|
ConnectionId = message.ConnectionId, |
|
|
@ -122,18 +127,25 @@ messageService.RegisterMessageHandler("chat", async (message) => |
|
|
|
payload = new |
|
|
|
{ |
|
|
|
message = "收到聊天消息", |
|
|
|
originalData = System.Text.Encoding.UTF8.GetString(message.Data) |
|
|
|
originalData = System.Text.Encoding.UTF8.GetString(message.Data), |
|
|
|
timestamp = DateTime.UtcNow |
|
|
|
} |
|
|
|
})), |
|
|
|
MessageType = System.Net.WebSockets.WebSocketMessageType.Text |
|
|
|
}; |
|
|
|
|
|
|
|
_logger.LogInformation("聊天消息处理完成,连接ID:{ConnectionId},响应数据大小:{DataSize}字节", |
|
|
|
message.ConnectionId, response.Data.Length); |
|
|
|
return response; |
|
|
|
}); |
|
|
|
|
|
|
|
messageService.RegisterMessageHandler("notification", async (message) => |
|
|
|
{ |
|
|
|
// 处理通知消息
|
|
|
|
_logger.LogInformation("开始处理通知消息,连接ID:{ConnectionId}", message.ConnectionId); |
|
|
|
_logger.LogDebug("原始消息数据:{Data}", System.Text.Encoding.UTF8.GetString(message.Data)); |
|
|
|
|
|
|
|
await Task.Delay(100); // 模拟异步处理
|
|
|
|
|
|
|
|
var response = new WebSocketMessage |
|
|
|
{ |
|
|
|
ConnectionId = message.ConnectionId, |
|
|
@ -143,11 +155,15 @@ messageService.RegisterMessageHandler("notification", async (message) => |
|
|
|
payload = new |
|
|
|
{ |
|
|
|
message = "收到通知消息", |
|
|
|
originalData = System.Text.Encoding.UTF8.GetString(message.Data) |
|
|
|
originalData = System.Text.Encoding.UTF8.GetString(message.Data), |
|
|
|
timestamp = DateTime.UtcNow |
|
|
|
} |
|
|
|
})), |
|
|
|
MessageType = System.Net.WebSockets.WebSocketMessageType.Text |
|
|
|
}; |
|
|
|
|
|
|
|
_logger.LogInformation("通知消息处理完成,连接ID:{ConnectionId},响应数据大小:{DataSize}字节", |
|
|
|
message.ConnectionId, response.Data.Length); |
|
|
|
return response; |
|
|
|
}); |
|
|
|
|
|
|
|