.NET 幫助

Socket io .NET(它如何為開發者運作)

發佈 2024年9月29日
分享:

Socket.IO 伺服器作為一個強大的庫,促進實時、雙向和事件驅動的通信。 它廣泛用於網路應用程式中,如聊天應用程式、實時更新和協作平台等任務。 雖然 Socket.IO 通常與 JavaScript 相關聯,但它也可以在用戶端使用 C# 有效運作。 有時候,客戶端可能是一個網頁瀏覽器。 在本文中,我們將探討如何在 C# 環境中設置和使用 Socket.IO 客戶端。 我們將介紹一些基本範例,最後總結其優勢和潛在的使用案例。

建立 Socket.IO 連接的方法

Socket.IO 可以使用不同的低層傳輸建立連接:

  • HTTP 長輪詢
  • Web Sockets

    • 網絡傳輸

    Socket io .NET(其工作原理對於開發人員):圖 1 - 客戶端-伺服器通信應用程序

在 Visual Studio 2022 中創建一個控制台專案

打開 Visual Studio,然後在起始窗口中選擇 建立新專案

Socket io .NET(開發人員運作方式):圖 2 - 顯示創建新專案視窗的截圖。

要在 Visual Studio 2022 中建立主控台應用程式,啟動 Visual Studio 並從開始視窗中選擇「建立新專案」。 選擇「控制台應用程式」範本,使用名稱和位置配置專案,並確保選擇 .NET 6.0。

什麼是Socket.IO?

Socket.IOJavaScript 庫,使網路客戶端和伺服器能夠進行即時通信。 它由兩部分組成:

Socket IO 的部分

  • 客戶端庫:在瀏覽器中運行。
  • 伺服器端庫:在 Node.js 上運行。

安裝必要的套件

在 .NET 應用程式中使用 Socket.IO 以 Visual Studio,您需要一個兼容的伺服器實作。 其中一個實現是SocketIoClientDotNet for .NET,允許一個Socket IO客戶端從C#應用程式連接到Socket.IO。

首先,安裝所需的 NuGet 套件。 您可以透過套件管理員主控台或將引用添加到您的專案文件來完成此操作。

Install-Package SocketIoClientDotNet
Install-Package SocketIoClientDotNet
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package SocketIoClientDotNet
VB   C#

SocketIoClientDotNet 套件的截圖

Socket io .NET(開發人員的運作方式):圖 3 - 使用解決方案的管理 NuGet 套件安裝 Socket.IO for NET,方法是在 NuGet 套件管理器的搜索欄中搜索「SocketIoClientDotNet」套件名稱,然後選擇項目並點擊安裝按鈕。

執行此命令將把 Socket.IO 客戶端庫整合到您的 .NET 專案中,使您的 C# 應用程式能夠連接到 Socket.IO 伺服器,促進用戶與系統之間的通訊。

創建 Socket.IO

在深入了解 C# 客戶端之前,我們先在 Visual Studio 中使用 .NET Core 控制台應用程式設置一個基本的 Socket IO 範例。 這將幫助我們測試客戶端的實施。

建立伺服器實作

以下程式碼在 C# 中設置了一個基本的 Socket.IO 伺服器,該伺服器在端口 3000 上監聽客戶端連接。當客戶端發送消息時,伺服器會記錄該消息並回應給客戶端,確認已收到。

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;
namespace DemoApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Connect to the Socket.IO server
            var socket = IO.Socket("http://localhost:3000");
            // Listen for the "connect" event
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                Console.WriteLine("Connected to the server!");
                // Emit a message to the server
                socket.Emit("message", "Hello from C# client!");
                // Listen for messages from the server
                socket.On("message", (data) =>
                {
                    Console.WriteLine("Message from server: " + data);
                });
            });
            // Listen for the "disconnect" event
            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                Console.WriteLine("Disconnected from the server!");
            });
            // Keep the console window open
            Console.ReadLine();
        }
    }
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;
namespace DemoApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Connect to the Socket.IO server
            var socket = IO.Socket("http://localhost:3000");
            // Listen for the "connect" event
            socket.On(Socket.EVENT_CONNECT, () =>
            {
                Console.WriteLine("Connected to the server!");
                // Emit a message to the server
                socket.Emit("message", "Hello from C# client!");
                // Listen for messages from the server
                socket.On("message", (data) =>
                {
                    Console.WriteLine("Message from server: " + data);
                });
            });
            // Listen for the "disconnect" event
            socket.On(Socket.EVENT_DISCONNECT, () =>
            {
                Console.WriteLine("Disconnected from the server!");
            });
            // Keep the console window open
            Console.ReadLine();
        }
    }
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports Quobject.SocketIoClientDotNet.Client
Namespace DemoApp
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Connect to the Socket.IO server
			Dim socket = IO.Socket("http://localhost:3000")
			' Listen for the "connect" event
			socket.On(Socket.EVENT_CONNECT, Sub()
				Console.WriteLine("Connected to the server!")
				' Emit a message to the server
				socket.Emit("message", "Hello from C# client!")
				' Listen for messages from the server
				socket.On("message", Sub(data)
					Console.WriteLine("Message from server: " & data)
				End Sub)
			End Sub)
			' Listen for the "disconnect" event
			socket.On(Socket.EVENT_DISCONNECT, Sub()
				Console.WriteLine("Disconnected from the server!")
			End Sub)
			' Keep the console window open
			Console.ReadLine()
		End Sub
	End Class
End Namespace
VB   C#

程式碼說明

在這個片段中,我們首先通過調用 IO.Socket 創建一個 Socket.IO 客戶端實例/發送者。("https://localhost:3000"),連接到客戶機上執行在端口 3000 的本地伺服器。

成功連接後 (Socket.EVENT_CONNECT)我們打印一條消息,表明我們已連接到伺服器。

然後,我們使用 socket.Emit 從客戶端向伺服器發送訊息。("message", "來自 C# 客戶端的問候"!請提供您想要翻譯的內容。). 這會發送包含內容 "Hello from C# client" 的訊息。!伺服器。

接下來,我們使用 socket.On 為 "message" 事件註冊回調,以便從伺服器接收消息。("訊息", (數據) => { ... }). 當伺服器發送「message」事件時,回調函式被調用,我們將接收到的訊息打印到控制台。

如果客戶端與伺服器的連線中斷 (Socket.EVENT_DISCONNECT),顯示斷開連接的訊息。

最後,使用 Console.ReadLine() 方法保持控制台窗口開啟,以便程式在執行後不會立即退出。 這讓我們能夠查看輸出並確保程式不會過早終止。

程式碼截圖

Socket io .NET(對開發人員的運作方式):圖4 - 範例程式碼

HTTP 長輪詢

長輪詢是一種用於網頁開發的技術,使用庫在客戶端之間發送消息。 (通常是網頁瀏覽器) 和伺服器。 它能夠透過在伺服器上觸發事件實現實時通信,這些事件可以被客戶端接收而無需持續輪詢。 此方法對於需要即時更新的應用程式特別有用,例如聊天應用程式或股票行情顯示器。

Socket io .NET(開發人員的工作原理):圖 5 - HTTP 長輪詢

Web Sockets

WebSocket 透過在單一 TCP 連線上建立全雙工通訊通道,以促進雙向通訊。 此協議允許客戶端(通常是網頁瀏覽器)與伺服器之間進行即時互動,使雙方能夠異步交換消息。

建立 WebSocket 通訊

客戶端向服務器發送 WebSocket 握手請求,表示其希望建立 WebSocket 連接。 伺服器在接收到握手請求後,會回應一個 WebSocket 握手回應,表示連線已成功建立。 透過 WebSocket 連接發送的訊息可以是任何格式。 (例如,文本或二進制) 並且可以非同步方式發送和接收。

網絡傳輸

Web Transport 作為一種尖端協議,引入了額外的功能來增強網路通信,超越了像 TCP 和 UDP 這些傳統協議的限制。通過利用 UDP 和 QUIC,它克服了前輩的不足,使其更加用戶友好和高效。 對於用戶而言,這轉化為降低延遲和改善擁塞控制,最終提供更流暢和更快速反應的網路體驗。 此外,Web Transport 提供了更好的安全措施,確保比 TCP 更安全的數據傳輸。隨著這些進步,Web Transport 減輕了數據傳輸中耗時的方面,優化了客戶端和服務器的整體性能。

以下是一個 Web Transport 在 web 應用程式中使用的基本範例:

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // The WebSocket URI
            string uri = "wss://echo.websocket.org";
            // Creating a new WebSocket connection
            using (ClientWebSocket webSocket = new ClientWebSocket())
            {
                await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
                Console.WriteLine("Connected to the server");
                // Sending data over the WebSocket
                byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
                await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
                Console.WriteLine("Data sent to the server");
                // Receiving data from the WebSocket
                byte[] receiveBuffer = new byte[1024];
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                byte[] data = new byte[result.Count];
                Array.Copy(receiveBuffer, data, result.Count);
                Console.WriteLine("Received data: " + BitConverter.ToString(data));
            }
        }
    }
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // The WebSocket URI
            string uri = "wss://echo.websocket.org";
            // Creating a new WebSocket connection
            using (ClientWebSocket webSocket = new ClientWebSocket())
            {
                await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
                Console.WriteLine("Connected to the server");
                // Sending data over the WebSocket
                byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
                await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
                Console.WriteLine("Data sent to the server");
                // Receiving data from the WebSocket
                byte[] receiveBuffer = new byte[1024];
                WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
                byte[] data = new byte[result.Count];
                Array.Copy(receiveBuffer, data, result.Count);
                Console.WriteLine("Received data: " + BitConverter.ToString(data));
            }
        }
    }
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Namespace SocketIO.Demo
	Friend Class Program
		Shared Async Function Main(ByVal args() As String) As Task
			' The WebSocket URI
			Dim uri As String = "wss://echo.websocket.org"
			' Creating a new WebSocket connection
			Using webSocket As New ClientWebSocket()
				Await webSocket.ConnectAsync(New Uri(uri), CancellationToken.None)
				Console.WriteLine("Connected to the server")
				' Sending data over the WebSocket
				Dim sendBuffer() As Byte = { 1, 2, 3, 4 }
				Await webSocket.SendAsync(New ArraySegment(Of Byte)(sendBuffer), WebSocketMessageType.Binary, True, CancellationToken.None)
				Console.WriteLine("Data sent to the server")
				' Receiving data from the WebSocket
				Dim receiveBuffer(1023) As Byte
				Dim result As WebSocketReceiveResult = Await webSocket.ReceiveAsync(New ArraySegment(Of Byte)(receiveBuffer), CancellationToken.None)
				Dim data(result.Count - 1) As Byte
				Array.Copy(receiveBuffer, data, result.Count)
				Console.WriteLine("Received data: " & BitConverter.ToString(data))
			End Using
		End Function
	End Class
End Namespace
VB   C#

在此範例中,我們首先使用 WebSocket URL 建立到伺服器的新 WebTransport 連接。 (wss://echo.websocket.org). 然後,我們在連接上建立一個雙向流並發送一些數據。 ([1, 2, 3, 4]) 在溪流上方。 最後,我們從流中讀取數據並記錄到控制台。

上述代碼的輸出

當您使用 WebSocket 回音伺服器運行應用程式時,輸出應類似如下所示:

Socket io .NET(開發者的工作原理):圖6 - 使用WebSocket URL的WebTransport連接的控制台輸出。

Web Transport 的優勢

現代替代方案: Web Transport 提供了一種傳統 web 通訊協議(如 TCP 和 UDP)的現代替代方案。

高效資料傳輸: 它通過利用多路傳輸流和進階特性來提供高效的資料傳輸。

高性能: 非常適合構建需要低延遲和可靠數據傳輸的高性能網絡應用程序。

多路復用流: 支持多路復用流,允許多個數據流在單一連接上同時發送和接收。

創新: 隨著網頁開發人員持續採用 Web Transport,我們可以預期看到更多在網頁通訊協議上的創新。

改進的用戶體驗: 採用 Web Transport 可以提高網站使用者的體驗,因為其資料傳輸速度更快且更可靠。

IronPDF 庫介紹

IronPDF 是一個專為使用C#的開發人員設計的全面.NET PDF庫。 這個強大的工具讓開發者能夠輕鬆地 建立, 操作,和 讀取 在其應用程式中使用 PDF 文件。 使用 IronPDF,開發人員可以從 HTML 字串, HTML 文件,和 網址,使其在各種使用情境中具有高度的靈活性。 此外,IronPDF 提供了高級 PDF 編輯功能,如添加標頭、頁尾、水印等。 通過 NuGet 套件管理器無縫整合到 C# 項目中,簡化了 PDF 文件的處理過程,精簡開發流程並提高生產力。

Socket io .NET(開發者如何使用):圖7 - IronPDF for .NET:C# PDF庫

使用 NuGet 套件管理器安裝

使用 NuGet 套件管理器在 Visual Studio 或從命令列安裝 IronPDF。 在 Visual Studio 中,進入控制台:

  • 工具 -> NuGet 套件管理器 -> 套件管理器控制台
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

IronPDF 代碼範例

這裡有一個簡單的例子,使用 IronPDF 要將數據位元轉換為 PDF 文件,請在 Main 方法中調用 GeneratePDF 方法,並將數據作為參數傳遞,如上例所示。

using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo 
{
 class Program
 {
     static async Task Main(string[] args)
     {
         // The WebSocket URI
         string uri = "wss://echo.websocket.org";
         // Creating a new WebSocket connection
         using (ClientWebSocket webSocket = new ClientWebSocket())
         {
             await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
             Console.WriteLine("Connected to the server");
             // Sending data over the WebSocket
             byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
             await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
             Console.WriteLine("Data sent to the server");
             // Receiving data from the WebSocket
             byte[] receiveBuffer = new byte[1024];
             WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
             byte[] data = new byte[result.Count];
             Array.Copy(receiveBuffer, data, result.Count);
             Console.WriteLine("Received data: " + BitConverter.ToString(data));
              // Data to Generate in PDF File
              string pdfData = BitConverter.ToString(data);
              PDFGenerator.GeneratePDF(pdfData);
         }
     }
 }
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo 
{
 class Program
 {
     static async Task Main(string[] args)
     {
         // The WebSocket URI
         string uri = "wss://echo.websocket.org";
         // Creating a new WebSocket connection
         using (ClientWebSocket webSocket = new ClientWebSocket())
         {
             await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
             Console.WriteLine("Connected to the server");
             // Sending data over the WebSocket
             byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
             await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
             Console.WriteLine("Data sent to the server");
             // Receiving data from the WebSocket
             byte[] receiveBuffer = new byte[1024];
             WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
             byte[] data = new byte[result.Count];
             Array.Copy(receiveBuffer, data, result.Count);
             Console.WriteLine("Received data: " + BitConverter.ToString(data));
              // Data to Generate in PDF File
              string pdfData = BitConverter.ToString(data);
              PDFGenerator.GeneratePDF(pdfData);
         }
     }
 }
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Namespace SocketIO.Demo
 Friend Class Program
	 Shared Async Function Main(ByVal args() As String) As Task
		 ' The WebSocket URI
		 Dim uri As String = "wss://echo.websocket.org"
		 ' Creating a new WebSocket connection
		 Using webSocket As New ClientWebSocket()
			 Await webSocket.ConnectAsync(New Uri(uri), CancellationToken.None)
			 Console.WriteLine("Connected to the server")
			 ' Sending data over the WebSocket
			 Dim sendBuffer() As Byte = { 1, 2, 3, 4 }
			 Await webSocket.SendAsync(New ArraySegment(Of Byte)(sendBuffer), WebSocketMessageType.Binary, True, CancellationToken.None)
			 Console.WriteLine("Data sent to the server")
			 ' Receiving data from the WebSocket
			 Dim receiveBuffer(1023) As Byte
			 Dim result As WebSocketReceiveResult = Await webSocket.ReceiveAsync(New ArraySegment(Of Byte)(receiveBuffer), CancellationToken.None)
			 Dim data(result.Count - 1) As Byte
			 Array.Copy(receiveBuffer, data, result.Count)
			 Console.WriteLine("Received data: " & BitConverter.ToString(data))
			  ' Data to Generate in PDF File
			  Dim pdfData As String = BitConverter.ToString(data)
			  PDFGenerator.GeneratePDF(pdfData)
		 End Using
	 End Function
 End Class
End Namespace
VB   C#

PDF 生成類別代碼

using IronPdf;
namespace SocketIO.Demo
{
    public class PDFGenerator
    {
        public static void GeneratePDF(string data)
        {
          IronPdf.License.LicenseKey = "Your-Licence-Key-Here";
          Console.WriteLine("PDF Generating Started...");
      // Instantiate Renderer
          var renderer = new ChromePdfRenderer();
          Console.WriteLine("PDF Processing ....");
          var pdf = renderer.RenderHtmlAsPdf(data);
          string filePath = "Data.pdf";
          pdf.SaveAs(filePath);
          Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}");
        }
    }
}
using IronPdf;
namespace SocketIO.Demo
{
    public class PDFGenerator
    {
        public static void GeneratePDF(string data)
        {
          IronPdf.License.LicenseKey = "Your-Licence-Key-Here";
          Console.WriteLine("PDF Generating Started...");
      // Instantiate Renderer
          var renderer = new ChromePdfRenderer();
          Console.WriteLine("PDF Processing ....");
          var pdf = renderer.RenderHtmlAsPdf(data);
          string filePath = "Data.pdf";
          pdf.SaveAs(filePath);
          Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}");
        }
    }
}
Imports IronPdf
Namespace SocketIO.Demo
	Public Class PDFGenerator
		Public Shared Sub GeneratePDF(ByVal data As String)
		  IronPdf.License.LicenseKey = "Your-Licence-Key-Here"
		  Console.WriteLine("PDF Generating Started...")
	  ' Instantiate Renderer
		  Dim renderer = New ChromePdfRenderer()
		  Console.WriteLine("PDF Processing ....")
		  Dim pdf = renderer.RenderHtmlAsPdf(data)
		  Dim filePath As String = "Data.pdf"
		  pdf.SaveAs(filePath)
		  Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}")
		End Sub
	End Class
End Namespace
VB   C#

輸出

Socket.io .NET(對開發人員的工作原理):圖8 - 使用Socket.IO和IronPDF的控制台輸出

在提供的程式碼中,IronPDF 用於從透過 WebSocket 連線收到的十六進位字串生成 PDF 文件。 GeneratePDF 方法使用授權金鑰初始化 IronPDF,並使用其 ChromePdfRenderer 實例通過 RenderHtmlAsPdf 方法將十六進位字串作為 HTML 內容渲染成 PDF。 您可以從以下位置獲取免費授權密鑰 這裡. 然後使用 SaveAs 方法將此 PDF 本地儲存為「Data.pdf」。 IronPDF 的整合可以將動態 WebSocket 數據無縫轉換為結構化 PDF 格式,展示了其在將實時數據流轉換為存檔文檔方面的實用性。

已生成 PDF 文件

Socket io .NET(開發人員的工作原理):圖 9 - 使用 IronPDF 生成的輸出 PDF

結論

利用 Socket.IO 使用C#為與連接客戶端的即時互動提供了眾多機會,不僅僅局限於JavaScript和Node.js的領域。 集成像 Socket.IOIronPDF 到您的 .NET 專案中,可以顯著增強即時通訊和 PDF 處理能力。 Socket.IO 促進了客戶端和伺服器之間流暢的即時雙向通信,而 IronPDF 提供強大的功能用於 創建操作 輕鬆處理 PDF 文件。

IronPDF 釋放其全部潛力,確保在您的 C# 應用程序中高效且可靠地生成和操作 PDF。

下一個 >
Junit Java(如何為開發者工作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >