C# websocket 创建多个房间 详细代码
时间: 2024-03-19 07:44:51 浏览: 137
下面是一个简单的 C# WebSocket 代码示例,用于创建多个房间:
```csharp
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;
namespace WebSocketServer
{
public class WebSocketRoom
{
private List<WebSocket> _sockets = new List<WebSocket>();
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public async Task AddSocketAsync(WebSocket socket)
{
_sockets.Add(socket);
await Task.Factory.StartNew(async () =>
{
while (socket.State == WebSocketState.Open)
{
var buffer = new byte[1024];
var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), _cancellationTokenSource.Token);
if (result.MessageType == WebSocketMessageType.Close)
{
await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
_sockets.Remove(socket);
break;
}
var message = $"{DateTime.Now.ToString("HH:mm:ss")} - {System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count)}";
foreach (var s in _sockets)
{
if (s.State == WebSocketState.Open)
{
await s.SendAsync(new ArraySegment<byte>(System.Text.Encoding.UTF8.GetBytes(message)), WebSocketMessageType.Text, true, CancellationToken.None);
}
}
}
}, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
public void Close()
{
_cancellationTokenSource.Cancel();
foreach (var s in _sockets)
{
if (s.State == WebSocketState.Open)
{
s.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
}
}
_sockets.Clear();
}
}
public class WebSocketServer
{
private HttpListener _listener;
private Dictionary<string, WebSocketRoom> _rooms = new Dictionary<string, WebSocketRoom>();
public async Task StartAsync(string url)
{
_listener = new HttpListener();
_listener.Prefixes.Add(url);
_listener.Start();
while (true)
{
var context = await _listener.GetContextAsync();
if (!context.Request.IsWebSocketRequest)
{
context.Response.StatusCode = 400;
context.Response.Close();
continue;
}
var socket = await context.AcceptWebSocketAsync(null);
var roomName = context.Request.QueryString["room"];
if (string.IsNullOrEmpty(roomName))
{
roomName = "default";
}
if (!_rooms.ContainsKey(roomName))
{
_rooms[roomName] = new WebSocketRoom();
}
await _rooms[roomName].AddSocketAsync(socket.WebSocket);
}
}
public void Stop()
{
_listener.Stop();
foreach (var room in _rooms.Values)
{
room.Close();
}
_rooms.Clear();
}
}
}
```
上面的代码使用了 `HttpListener` 和 `WebSocket` 类来实现一个简单的 WebSocket 服务器,其中 `WebSocketRoom` 类表示一个房间,`WebSocketServer` 类表示整个服务器。在 `WebSocketServer.StartAsync` 方法中,我们通过解析 URL 中的查询参数来创建不同的房间。当有新的客户端连接时,我们将其添加到对应的房间中,然后启动一个新的线程来接收客户端消息并将其广播给该房间中的所有客户端。在 `WebSocketRoom.Close` 方法中,我们将关闭该房间中所有的客户端连接。
使用时,可以按照以下方式启动服务器:
```csharp
var server = new WebSocketServer();
await server.StartAsync("http://localhost:8080/");
```
然后在浏览器中访问 URL `http://localhost:8080/?room=myroom`,即可加入名为 `myroom` 的房间。在浏览器的 JavaScript 中,可以使用 `WebSocket` 对象来与服务器进行通信,示例代码如下:
```javascript
var socket = new WebSocket("ws://localhost:8080/?room=myroom");
socket.onmessage = function(event) {
console.log("Received message:", event.data);
};
socket.send("Hello, world!");
```
阅读全文