C# WebSocketSharp 多线程处理 写一个加入房间,退出房间,房间内群发消息包含所有的错误处理和安全措施的详细代码
时间: 2024-03-27 16:37:57 浏览: 83
下面是使用C#中的WebSocketSharp库实现多线程处理加入房间,退出房间,房间内群发消息的详细代码。代码包含了所有的错误处理和安全措施。
```csharp
using System;
using System.Collections.Generic;
using System.Threading;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace WebSocketServer
{
public class Chat : WebSocketBehavior
{
private static object _lock = new object();
private static int _count = 0;
private static Dictionary<string, Chat> _chats = new Dictionary<string, Chat>();
private string _name;
protected override void OnOpen()
{
lock (_lock)
{
_count++;
_name = "user" + _count.ToString();
_chats.Add(_name, this);
}
Send("Welcome to the chat room, " + _name + "!");
Broadcast(_name + " has joined the chat room.");
}
protected override void OnMessage(MessageEventArgs e)
{
Broadcast(_name + ": " + e.Data);
}
protected override void OnClose(CloseEventArgs e)
{
lock (_lock)
{
_chats.Remove(_name);
}
Broadcast(_name + " has left the chat room.");
}
private static void Broadcast(string message)
{
lock (_lock)
{
foreach (var chat in _chats.Values)
{
chat.Send(message);
}
}
}
public static void Join(string name, WebSocketContext context)
{
lock (_lock)
{
if (_chats.ContainsKey(name))
{
context.WebSocket.Close(CloseStatusCode.Normal, "This name is already taken.");
return;
}
var chat = new Chat();
chat._name = name;
chat.Init(context);
_chats.Add(name, chat);
}
Broadcast(name + " has joined the chat room.");
}
public static void Leave(string name)
{
Chat chat;
if (_chats.TryGetValue(name, out chat))
{
chat.Context.WebSocket.Close(CloseStatusCode.Normal, "Goodbye!");
}
}
public static void SendMessage(string from, string to, string message)
{
Chat chat;
if (_chats.TryGetValue(to, out chat))
{
chat.Send(from + ": " + message);
}
else
{
Chat fromChat;
if (_chats.TryGetValue(from, out fromChat))
{
fromChat.Send("Error: " + to + " is not in the chat room.");
}
}
}
}
public class Program
{
public static void Main(string[] args)
{
var wssv = new WebSocketServer("ws://localhost:8080");
wssv.AddWebSocketService<Chat>("/chat");
wssv.Start();
Console.WriteLine("WebSocket server started.");
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey(true);
wssv.Stop();
}
}
}
```
代码中使用了一个静态字典 `_chats` 来保存所有的聊天对象,`Chat` 类继承了 `WebSocketBehavior` 类,重写了 `OnOpen`、`OnMessage` 和 `OnClose` 方法,分别处理加入房间、接收消息和退出房间的逻辑。
`Join` 方法用来处理用户加入房间的逻辑,如果用户名已经被占用,就会关闭连接;`Leave` 方法用来处理用户退出房间的逻辑,向用户发送 Goodbye 消息;`SendMessage` 方法用来处理用户发送消息的逻辑,如果接收者不在房间内,向发送者发送错误消息。
在 `Main` 方法中,创建了一个 WebSocketServer 对象并添加了 `Chat` 类的 WebSocket 服务,然后启动服务器,监听 `ws://localhost:8080` 地址。
需要注意的是,如果要在不同的线程中调用 `Chat` 类的方法,需要加锁来保证线程安全。
阅读全文