温馨提示×

c# websocketserver怎样运行

c#
小樊
83
2024-12-02 16:43:55
栏目: 编程语言

要在C#中创建并运行一个WebSocket服务器,你可以使用System.Net.WebSockets命名空间中的WebSocket类。以下是一个简单的WebSocket服务器示例:

  1. 首先,确保你的项目已经引用了System.Net.WebSockets命名空间。在Visual Studio中,右键单击项目,选择“添加引用”,然后在“程序集”选项卡中找到并添加System.Net.WebSockets

  2. 创建一个名为WebSocketServer的新类,并在其中添加以下代码:

using System;
using System.Net.WebSockets;
using System.Threading.Tasks;

namespace WebSocketServer
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // 定义WebSocket服务器的URI
            string uri = "ws://localhost:5000";

            // 创建WebSocket服务器
            using (var server = new WebSocketServer(uri))
            {
                // 开始监听客户端连接
                await server.StartAsync();

                Console.WriteLine("WebSocket服务器正在运行...");

                // 等待客户端连接
                await server.WaitForClientConnectionAsync();

                // 处理客户端消息
                await server.HandleClientMessageAsync();
            }
        }
    }

    public class WebSocketServer
    {
        private readonly WebSocket _webSocket;

        public WebSocketServer(string uri)
        {
            _webSocket = new WebSocket(uri);
        }

        public async Task StartAsync()
        {
            // 添加WebSocket事件处理程序
            _webSocket.ClientConnected += WebSocket_ClientConnected;
            _webSocket.ClientError += WebSocket_ClientError;
            _webSocket.ClientMessageReceived += WebSocket_ClientMessageReceived;
            _webSocket.ClientDisconnected += WebSocket_ClientDisconnected;

            // 开始监听客户端连接
            await _webSocket.StartAsync();
        }

        public async Task WaitForClientConnectionAsync()
        {
            byte[] buffer = new byte[1024 * 4];
            WebSocketReceiveResult result;

            do
            {
                result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }
            while (!result.CloseStatus.HasValue);
        }

        public async Task HandleClientMessageAsync()
        {
            byte[] buffer = new byte[1024 * 4];
            WebSocketReceiveResult result;

            do
            {
                result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

                // 处理客户端消息
                string message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                Console.WriteLine($"收到客户端消息: {message}");

                // 发送响应给客户端
                string response = "服务器已收到您的消息";
                byte[] responseBytes = Encoding.UTF8.GetBytes(response);
                await _webSocket.SendAsync(new ArraySegment<byte>(responseBytes), result.MessageType, result.CloseStatus.Value == WebSocketCloseStatus.NormalClosure, CancellationToken.None);
            }
            while (!result.CloseStatus.HasValue);
        }

        private void WebSocket_ClientConnected(object sender, WebSocketClientConnectedEventArgs e)
        {
            Console.WriteLine($"客户端已连接: {e.ClientId}");
        }

        private void WebSocket_ClientError(object sender, WebSocketErrorEventArgs e)
        {
            Console.WriteLine($"客户端错误: {e.Exception}");
        }

        private void WebSocket_ClientMessageReceived(object sender, WebSocketClientMessageReceivedEventArgs e)
        {
            Console.WriteLine($"客户端消息已接收: {e.Message}");
        }

        private void WebSocket_ClientDisconnected(object sender, WebSocketClientDisconnectedEventArgs e)
        {
            Console.WriteLine($"客户端已断开连接: {e.ClientId}");
        }
    }
}
  1. 运行WebSocketServer程序。服务器将在端口5000上监听客户端连接。

  2. 使用支持WebSocket的客户端(如浏览器或其他WebSocket库)连接到服务器并发送消息。服务器将接收到的消息原样返回给客户端。

注意:这个示例仅用于演示目的,实际应用中你可能需要添加更多的错误处理和功能。

0