c#开发 websocketserver 给指定客服端发信息
时间: 2024-11-10 17:25:10 浏览: 11
C#+Websocket技术+客户端与服务信息握手_(聊天室Demo)
5星 · 资源好评率100%
在 C# 中,你可以使用 System.Net.WebSockets API 来创建一个 WebSocket 服务器,允许向特定客户端发送消息。以下是一个简单的步骤概述:
1. 引入必要的库:
```csharp
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebSockets;
```
2. 创建WebSocket中间件:
```csharp
public static IApplicationBuilder UseWebSockets(this IApplicationBuilder builder)
{
return builder.UseMiddleware<WebSocketServerMiddleware>();
}
```
3. 定义 `WebSocketServerMiddleware` 类:
```csharp
public class WebSocketServerMiddleware
{
private readonly RequestDelegate _next;
public WebSocketServerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.WebSockets.IsWebSocketRequest)
{
var socket = await context.WebSockets.AcceptWebSocketAsync();
var clients = new Dictionary<string, WebSocket>();
// 添加新连接到字典
clients.Add(socket.ConnectionId, socket);
try
{
while (true)
{
var message = await socket.ReceiveMessageAsync();
// 根据需求判断是否给指定客户端发送信息
if (IsTargetClient(clients, "your-target-client-id")) // 替换为实际的客户端ID
{
await SendToSpecificClient(socket, message);
}
}
}
catch (WebSocketCloseStatus wsCloseStatus)
{
Console.WriteLine($"Connection closed by client: {wsCloseStatus}");
}
finally
{
// 断开连接时从字典中移除
clients.Remove(socket.ConnectionId);
}
}
else
{
await _next(context);
}
}
private bool IsTargetClient(Dictionary<string, WebSocket> clients, string targetClientId)
{
return clients.ContainsKey(targetClientId);
}
private async Task SendToSpecificClient(WebSocket socket, Message receivedMessage)
{
// 构建并发送回特定客户端的消息
var messageBytes = Encoding.UTF8.GetBytes("Your message here");
await socket.SendAsync(new ArraySegment<byte>(messageBytes), WebSocketMessageType.Text, true);
}
}
```
4. 在启动应用程序时启用WebSocket服务:
```csharp
app.UseWebSockets();
```
在这个例子中,你需要有一个标识目标客户端的方法(如 `IsTargetClient`),以及一个将消息发送到指定客户端的方法(如 `SendToSpecificClient`)。你需要替换掉“your-target-client-id”和“Your message here”以适应你的实际需求。
阅读全文