C# websocket 创建多个房间 添加用户,开启服务器,房间发送消息 详细代码
时间: 2024-04-05 11:29:37 浏览: 65
C# 开发 websocket 服务端和客户端
以下是一个简单的C# WebSocket服务器示例,可以创建多个房间,添加用户,并在房间之间发送消息。注意:这只是一个示例,应该根据具体需求进行修改和扩展。
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketServer
{
class Program
{
// 房间列表
static Dictionary<string, List<WebSocket>> rooms = new Dictionary<string, List<WebSocket>>();
static async Task Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
Console.WriteLine("WebSocket server started.");
while (true)
{
HttpListenerContext context = await listener.GetContextAsync();
if (context.Request.IsWebSocketRequest)
{
ProcessWebSocketRequest(context);
}
else
{
// 处理普通HTTP请求
}
}
}
static async void ProcessWebSocketRequest(HttpListenerContext context)
{
WebSocketContext webSocketContext = null;
try
{
webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null);
Console.WriteLine("WebSocket connected.");
// 处理WebSocket连接
await ProcessWebSocketConnection(webSocketContext.WebSocket);
}
catch (Exception ex)
{
Console.WriteLine("WebSocket error: " + ex.Message);
if (webSocketContext != null)
{
webSocketContext.WebSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, "WebSocket error", CancellationToken.None);
}
}
}
static async Task ProcessWebSocketConnection(WebSocket webSocket)
{
// 进入房间
string roomName = "default";
if (!rooms.ContainsKey(roomName))
{
rooms[roomName] = new List<WebSocket>();
}
rooms[roomName].Add(webSocket);
while (webSocket.State == WebSocketState.Open)
{
byte[] buffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
if (result.MessageType == WebSocketMessageType.Text)
{
string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
Console.WriteLine("Received message: " + message);
// 广播消息到房间内的其他用户
foreach (WebSocket socket in rooms[roomName])
{
if (socket != webSocket && socket.State == WebSocketState.Open)
{
await socket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
else if (result.MessageType == WebSocketMessageType.Close)
{
// 离开房间
rooms[roomName].Remove(webSocket);
break;
}
}
Console.WriteLine("WebSocket closed.");
}
}
}
```
要创建多个房间,可以在`rooms`字典中添加新的条目。在进入房间时,根据需要选择合适的房间名称,例如从HTTP请求参数中获取。在发送消息时,广播消息到房间内的其他用户即可。
阅读全文