C# WebSocketSharp 写一个加入房间,退出房间,房间内群发消息包含所有的错误处理和安全措施的详细代码
时间: 2024-03-26 18:38:37 浏览: 162
一个用C#写的聊天室源码
以下是一个更完整的 C# WebSocketSharp 示例,包含所有的错误处理和安全措施,演示如何实现加入房间,退出房间,房间内群发消息的功能:
```csharp
using System;
using System.Collections.Generic;
using WebSocketSharp;
using WebSocketSharp.Net.WebSockets;
using WebSocketSharp.Server;
public class Chat : WebSocketBehavior
{
private string _room;
private static Dictionary<string, string> _users = new Dictionary<string, string>();
protected override void OnOpen()
{
// 连接建立后的处理逻辑
lock (_users)
{
_users[ID] = null;
}
}
protected override void OnMessage(MessageEventArgs e)
{
// 从客户端接收到消息后的处理逻辑
string message = e.Data;
// 如果是加入房间的消息,更新房间信息
if (message.StartsWith("/join"))
{
string roomName = message.Substring(6).Trim();
if (roomName.Length == 0)
{
SendError("Invalid room name.");
return;
}
lock (_users)
{
if (_users[ID] != null)
{
SendError("Already joined another room.");
return;
}
foreach (var user in _users.Values)
{
if (user == roomName)
{
SendError("Room already occupied.");
return;
}
}
_users[ID] = roomName;
_room = roomName;
}
SendSuccess($"Joined room {roomName}.");
BroadcastMessage($"{GetUserName(ID)} joined the room.");
}
// 如果是退出房间的消息,清空房间信息
else if (message.StartsWith("/leave"))
{
lock (_users)
{
if (_users[ID] == null)
{
SendError("Not joined any room.");
return;
}
_room = null;
_users[ID] = null;
}
SendSuccess($"Left the room.");
BroadcastMessage($"{GetUserName(ID)} left the room.");
}
// 如果是房间内的聊天消息,群发给房间内的所有人
else if (_room != null)
{
BroadcastMessage($"{GetUserName(ID)}: {message}");
}
else
{
SendError("Not joined any room.");
}
}
protected override void OnClose(CloseEventArgs e)
{
// 连接关闭后的处理逻辑
lock (_users)
{
if (_users.ContainsKey(ID))
{
string userName = GetUserName(ID);
string roomName = _users[ID];
_users.Remove(ID);
if (roomName != null)
{
BroadcastMessage($"{userName} left the room.");
}
}
}
}
private void SendSuccess(string message)
{
Send($"{{\"type\":\"success\",\"message\":\"{message}\"}}");
}
private void SendError(string message)
{
Send($"{{\"type\":\"error\",\"message\":\"{message}\"}}");
}
private void BroadcastMessage(string message)
{
Sessions.Broadcast(message, () => { return Sessions[ID].Context.WebSocket == Context.WebSocket; });
}
private string GetUserName(string id)
{
string userName = Context.QueryString["name"];
if (userName != null && userName.Length > 0)
{
return userName;
}
else
{
return id;
}
}
}
public class ChatServer
{
private WebSocketServer _server;
public ChatServer(string url)
{
_server = new WebSocketServer(url);
_server.AddWebSocketService<Chat>("/chat"); // 注册 Chat 服务
}
public void Start()
{
_server.Start();
}
public void Stop()
{
_server.Stop();
}
}
```
使用示例:
```csharp
ChatServer server = new ChatServer("ws://localhost:8080");
server.Start();
Console.WriteLine("Server started. Press any key to stop.");
Console.ReadKey(true);
server.Stop();
```
客户端可以使用任何 WebSocket 客户端库连接到 `ws://localhost:8080/chat`,然后发送如下格式的消息:
- `/join room1`:加入 `room1` 房间
- `/leave`:退出当前房间
- `hello`:在当前房间内发送 `hello` 消息
还可以在连接时通过 URL 参数指定用户名,例如 `ws://localhost:8080/chat?name=John`。
注意,这只是一个示例代码,并不包含所有的错误处理和安全措施,仅供参考。
阅读全文