.NET控制台WebSocket应用:客户端下拉展示与设备分类实现
.NET WebSocket客户端展示与设备分类实现
一、后端维护客户端与设备信息
首先需要在.NET控制台应用中维护已连接客户端的元数据(包括设备类型),并提供接口让前端获取该列表。
1. 定义客户端模型
创建类存储客户端核心信息:
public class ConnectedClient { public string ConnectionId { get; set; } public string DeviceType { get; set; } // 存储Android/iOS/Windows等类型 public WebSocket WebSocket { get; set; } }
2. 线程安全的客户端集合
使用ConcurrentDictionary维护已连接客户端,避免多线程冲突:
private static readonly ConcurrentDictionary<string, ConnectedClient> _connectedClients = new();
3. 收集设备类型信息
客户端建立WebSocket连接时,通过URL参数或请求头传递设备类型,后端读取后将客户端加入集合:
// 示例:基于ASP.NET Core WebSocket中间件 app.Use(async (context, next) => { if (context.Request.Path == "/ws") { if (context.WebSockets.IsWebSocketRequest) { // 从URL参数读取设备类型 var deviceType = context.Request.Query["deviceType"].FirstOrDefault() ?? "Unknown"; using var webSocket = await context.WebSockets.AcceptWebSocketAsync(); var client = new ConnectedClient { ConnectionId = Guid.NewGuid().ToString(), DeviceType = deviceType, WebSocket = webSocket }; _connectedClients.TryAdd(client.ConnectionId, client); // 执行你的现有消息通信逻辑 await HandleWebSocketMessages(webSocket, client.ConnectionId); // 客户端断开后移除记录 _connectedClients.TryRemove(client.ConnectionId, out _); } else { context.Response.StatusCode = StatusCodes.Status400BadRequest; } } else { await next(); } });
4. 提供客户端列表接口
添加HTTP接口让前端获取已连接客户端数据(以ASP.NET Core最小API为例):
app.MapGet("/api/connected-clients", () => { var clientList = _connectedClients.Values .Select(c => new { c.ConnectionId, c.DeviceType }) .ToList(); return Results.Ok(clientList); });
二、前端实现分类下拉列表
前端通过定时请求后端接口获取数据,按设备类型分组后渲染下拉列表。
1. 设备类型识别(网页客户端)
用JS识别当前设备类型,建立WebSocket连接时传递给后端:
function getDeviceType() { const ua = navigator.userAgent; if (ua.includes('Android')) return 'Android'; if (ua.includes('iPhone') || ua.includes('iPad')) return 'iOS'; if (ua.includes('Windows')) return 'Windows'; if (ua.includes('Macintosh')) return 'macOS'; if (ua.includes('Ubuntu')) return 'Ubuntu'; return 'Unknown'; } // 建立WebSocket连接 const deviceType = getDeviceType(); const socket = new WebSocket(`ws://localhost:5000/ws?deviceType=${deviceType}`);
2. 获取并分组客户端数据
定时请求后端接口,将客户端按设备类型分组:
async function fetchConnectedClients() { const res = await fetch('/api/connected-clients'); return await res.json(); } function groupClientsByDevice(clients) { return clients.reduce((groups, client) => { const type = client.DeviceType; groups[type] = groups[type] || []; groups[type].push(client); return groups; }, {}); }
3. 渲染分类下拉列表
用HTML的<optgroup>实现分组下拉:
<select id="clientDropdown" style="width: 300px;"> <option value="">选择客户端</option> </select>
function renderDropdown(groupedClients) { const dropdown = document.getElementById('clientDropdown'); dropdown.innerHTML = '<option value="">选择客户端</option>'; Object.entries(groupedClients).forEach(([deviceType, clients]) => { const optGroup = document.createElement('optgroup'); optGroup.label = deviceType; clients.forEach(client => { const option = document.createElement('option'); option.value = client.ConnectionId; option.textContent = `客户端 ${client.ConnectionId}`; optGroup.appendChild(option); }); dropdown.appendChild(optGroup); }); } // 每5秒刷新一次客户端列表 setInterval(async () => { const clients = await fetchConnectedClients(); const grouped = groupClientsByDevice(clients); renderDropdown(grouped); }, 5000);
三、注意事项
- 客户端断开连接时,后端需及时从集合中移除对应条目,避免展示无效数据。
- 设备类型识别逻辑可根据需求扩展,比如识别更多Linux发行版或特殊设备。
- 生产环境需添加身份验证,防止未授权用户获取客户端列表。
内容的提问来源于stack exchange,提问作者Hasan Ozan
相关产品推荐
相关产品推荐

