91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

c# websocket服務器搭建的方法是什么

小億
144
2024-01-08 21:34:28
欄目: 云計算

在C#中搭建WebSocket服務器的方法是通過使用WebSocket類和相關的命名空間來實現。

以下是一個簡單的例子:

  1. 首先,確保你的項目引用了System.Net.WebSockets命名空間。

  2. 創建一個WebSocket服務器端的類,并在其中初始化WebSocket對象。例如:

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

public class MyWebSocketServer
{
    private HttpListener _httpListener;
    private CancellationTokenSource _cts;

    public MyWebSocketServer(string url)
    {
        _httpListener = new HttpListener();
        _httpListener.Prefixes.Add(url);
        _cts = new CancellationTokenSource();
    }

    public async Task Start()
    {
        _httpListener.Start();
        Console.WriteLine("WebSocket server started.");

        while (!_cts.Token.IsCancellationRequested)
        {
            HttpListenerContext context = await _httpListener.GetContextAsync();
            if (context.Request.IsWebSocketRequest)
            {
                ProcessWebSocketRequest(context);
            }
            else
            {
                // Handle non-WebSocket request
                context.Response.StatusCode = 400;
                context.Response.Close();
            }
        }
    }

    private async void ProcessWebSocketRequest(HttpListenerContext context)
    {
        HttpListenerWebSocketContext webSocketContext = null;

        try
        {
            webSocketContext = await context.AcceptWebSocketAsync(subProtocol: null);
            Console.WriteLine("WebSocket connection established.");

            await HandleWebSocketConnection(webSocketContext.WebSocket);
        }
        catch (Exception ex)
        {
            Console.WriteLine("WebSocket connection failed: " + ex.Message);
            if (webSocketContext != null)
            {
                webSocketContext.WebSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, "Internal Server Error", CancellationToken.None);
            }
        }
    }

    private async Task HandleWebSocketConnection(WebSocket webSocket)
    {
        byte[] buffer = new byte[1024];
        WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);

        while (!result.CloseStatus.HasValue)
        {
            // Handle received data
            string receivedMessage = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
            Console.WriteLine("Received: " + receivedMessage);

            // Echo the received message back to the client
            await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), WebSocketMessageType.Text, true, CancellationToken.None);

            // Get next message
            result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
        }

        await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        Console.WriteLine("WebSocket connection closed.");
    }

    public void Stop()
    {
        _cts.Cancel();
        _httpListener.Stop();
        _httpListener.Close();
    }
}
  1. 在程序的入口點創建一個MyWebSocketServer實例并啟動服務器。例如:
class Program
{
    static async Task Main(string[] args)
    {
        string url = "http://localhost:8080/";
        MyWebSocketServer server = new MyWebSocketServer(url);
        await server.Start();

        Console.WriteLine("Press any key to stop the server.");
        Console.ReadKey();

        server.Stop();
    }
}

以上代碼創建了一個簡單的WebSocket服務器,監聽指定的URL,并處理接收到的WebSocket連接和消息。你可以根據自己的需求進行修改和擴展。

0
江都市| 朝阳区| 抚远县| 平邑县| 河北省| 平谷区| 肃宁县| 左贡县| 清流县| 辰溪县| 海盐县| 尚义县| 和政县| 绥芬河市| 桐梓县| 博兴县| 兰坪| 濮阳市| 民勤县| 边坝县| 延寿县| 温宿县| 清丰县| 恩平市| 磐安县| 林周县| 贞丰县| 海南省| 许昌县| 土默特左旗| 丰宁| 随州市| 通化县| 阳泉市| 砚山县| 梁河县| 济阳县| 子洲县| 垦利县| 精河县| 阜新市|