温馨提示×

c# websocketserver如何处理连接

c#
小樊
90
2024-12-02 16:46:56
栏目: 编程语言

在C#中,处理WebSocket连接通常需要使用System.Net.WebSockets命名空间中的WebSocket类。以下是一个简单的示例,展示了如何创建一个基本的WebSocket服务器来处理连接:

  1. 首先,确保在项目中引用了System.Net.WebSockets命名空间。在.csproj文件中添加以下引用:
<PackageReference Include="System.Net.WebSockets" Version="4.5.3" />
  1. 创建一个WebSocket服务器类,如下所示:
using System;
using System.Net.WebSockets;
using System.Threading.Tasks;

public class WebSocketServer
{
    private const string Uri = "ws://localhost:8080/websocket";
    private readonly WebSocketServer _server;

    public WebSocketServer()
    {
        _server = new WebSocketServer(Uri);
    }

    public async Task StartAsync()
    {
        _server.Start();
        Console.WriteLine("WebSocket server started on {0}", Uri);

        while (_server.State == WebSocketServerState.Running)
        {
            var result = await _server.AcceptWebSocketAsync();
            HandleClientConnected(result.WebSocket);
        }
    }

    private void HandleClientConnected(WebSocket webSocket)
    {
        Console.WriteLine("Client connected: {0}", webSocket.Id);

        _ = webSocket.ReceiveAsync(new ArraySegment<byte>(new byte[1024 * 4]), CancellationToken.None)
            .ContinueWith(t =>
            {
                if (t.IsCompletedSuccessfully)
                {
                    var receivedData = t.Result.ToArray();
                    Console.WriteLine($"Received data: {System.Text.Encoding.UTF8.GetString(receivedData)}");

                    _ = webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("Message received")), WebSocketMessageType.Text, true, CancellationToken.None)
                        .ContinueWith(t =>
                        {
                            if (t.IsCompletedSuccessfully)
                            {
                                Console.WriteLine("Message sent to client");
                            }
                        });
                }
            });
    }
}
  1. 创建一个WebSocketServerState枚举和一个WebSocketServer类,如下所示:
public enum WebSocketServerState
{
    Stopped,
    Running
}

public class WebSocketServer
{
    private readonly Uri _uri;
    private WebSocket _webSocket;
    private WebSocketServerState _state;

    public WebSocketServer(Uri uri)
    {
        _uri = uri;
        _state = WebSocketServerState.Stopped;
    }

    public WebSocketServerState State
    {
        get => _state;
        private set
        {
            _state = value;
            Console.WriteLine($"WebSocket server state changed to: {_state}");
        }
    }

    public async Task StartAsync()
    {
        State = WebSocketServerState.Running;
        var listener = new HttpListener();
        listener.Prefixes.Add(_uri);

        listener.Start();
        Console.WriteLine("WebSocket server started on {0}", _uri);

        while (State == WebSocketServerState.Running)
        {
            var context = await listener.GetContextAsync();
            if (context.Request.HttpMethod == "GET")
            {
                var request = new HttpWebSocketContext(context, _uri);
                _webSocket = request.WebSocket;
                HandleClientConnected(_webSocket);
            }
        }
    }

    public async Task AcceptWebSocketAsync()
    {
        return await _webSocket.AcceptWebSocketAsync();
    }
}
  1. 最后,在Main方法中启动WebSocket服务器:
public static async Task Main(string[] args)
{
    var server = new WebSocketServer();
    await server.StartAsync();
}

现在,当客户端连接到WebSocket服务器时,服务器将接收到的消息原样发送回客户端。你可以根据需要扩展此示例以处理更复杂的场景,例如发送消息到特定客户端或广播消息给所有连接的客户端。

0