C# websocket_sharp使用详细

        #region websocket-sharp

        public void websocket_sharp() {
            try {

                var url = "ws://121.40.165.18:8800";

                using (var ws = new WebSocketSharp.WebSocket(url)) {
                    var result = "";
                    ws.Connect();
                    ws.OnMessage += (sender, e) =>
                        result = e.Data;

                    while (true) {
                        if (result.Length <= 0) continue;
                        if (!string.IsNullOrWhiteSpace(result))
                        Console.WriteLine(result);
                        result = "";
                        Thread.Sleep(100);
                    }

                }

            } catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
        }

        #endregion

这里是一个完整的 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 添加到服务器中。然后,我们创建了一个新的聊天室,并等待用户输入以停止服务器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值