C# websocket 创建房间 详细代码
时间: 2024-03-17 15:45:22 浏览: 18
这里是一个完整的 C# WebSocket 创建聊天室的示例代码,包括创建 WebSocket 服务器对象、实现 Echo 类、实现 ChatRoomManager 类等。
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace WebSocketChatRoom
{
class ChatRoom
{
private string _roomId;
private List<WebSocket> _clients;
public ChatRoom(string roomId)
{
_roomId = roomId;
_clients = new List<WebSocket>();
}
public void AddClient(WebSocket client)
{
_clients.Add(client);
}
public void RemoveClient(WebSocket client)
{
_clients.Remove(client);
}
public void Broadcast(string message)
{
foreach (var client in _clients)
{
client.Send(message);
}
}
}
class ChatRoomManager
{
private static List<ChatRoom> _activeRooms = new List<ChatRoom>();
public static void CreateNewRoom()
{
// Generate a unique ID for the new chat room
string roomId = Guid.NewGuid().ToString();
// Create a new chat room object
var room = new ChatRoom(roomId);
// Add the chat room to the list of active chat rooms
_activeRooms.Add(room);
}
public static string GetAvailableRoomId()
{
// Find the first available chat room ID
for (int i = 0; i < 100; i++)
{
string roomId = i.ToString("D2");
if (!_activeRooms.Any(r => r.RoomId == roomId))
{
return roomId;
}
}
throw new ApplicationException("No available chat room ID found.");
}
public static void JoinRoom(string roomId, WebSocket client)
{
// Find the chat room with the specified ID
var room = _activeRooms.FirstOrDefault(r => r.RoomId == roomId);
if (room == null)
{
throw new ApplicationException($"Chat room with ID {roomId} not found.");
}
// Add the client to the chat room
room.AddClient(client);
// Send a welcome message to the client
client.Send($"Welcome to chat room {roomId}!");
}
public static void LeaveRoom(string roomId, WebSocket client)
{
// Find the chat room with the specified ID
var room = _activeRooms.FirstOrDefault(r => r.RoomId == roomId);
if (room == null)
{
throw new ApplicationException($"Chat room with ID {roomId} not found.");
}
// Remove the client from the chat room
room.RemoveClient(client);
}
public static void Broadcast(string roomId, string message)
{
// Find the chat room with the specified ID
var room = _activeRooms.FirstOrDefault(r => r.RoomId == roomId);
if (room == null)
{
throw new ApplicationException($"Chat room with ID {roomId} not found.");
}
// Broadcast the message to all clients in the chat room
room.Broadcast(message);
}
}
class ChatRoomBehavior : WebSocketBehavior
{
private string _roomId;
protected override void OnOpen()
{
// Get the ID of the new chat room
string roomId = ChatRoomManager.GetAvailableRoomId();
// Join the chat room
ChatRoomManager.JoinRoom(roomId, this);
// Save the chat room ID to the behavior object
_roomId = roomId;
}
protected override void OnMessage(MessageEventArgs e)
{
// Broadcast the message to all clients in the chat room
ChatRoomManager.Broadcast(_roomId, e.Data);
}
protected override void OnClose(CloseEventArgs e)
{
// Leave the chat room
ChatRoomManager.LeaveRoom(_roomId, this);
}
}
class Program
{
static void Main(string[] args)
{
// Create a WebSocket server on port 8080
var wssv = new WebSocketServer(8080);
// Add the ChatRoom behavior to the server
wssv.AddWebSocketService<ChatRoomBehavior>("/ChatRoom");
// Start the server
wssv.Start();
// Create a new chat room
ChatRoomManager.CreateNewRoom();
// Wait for input to stop the server
Console.WriteLine("Press any key to stop the server...");
Console.ReadLine();
// Stop the server
wssv.Stop();
}
}
}
```
在这个示例代码中,我们创建了一个 ChatRoom 类,用于表示聊天室对象;创建了一个 ChatRoomManager 类,用于管理聊天室;创建了一个 ChatRoomBehavior 类,用于处理客户端的 WebSocket 请求。在 Main 方法中,我们创建了一个 WebSocket 服务器对象,并将 ChatRoomBehavior 添加到服务器中。然后,我们创建了一个新的聊天室,并等待用户输入以停止服务器。