.NET 幫助

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

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.IO,是一個JavaScript函式庫,使得網頁用戶端和伺服器能夠進行即時通訊。 它由兩部分組成:

Socket IO 的部分

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

安裝必要的套件

Visual Studio中使用 Socket.IO 用於 .NET 應用程式時,您需要一個相容的伺服器實現。 其中一個實作是用於 .NET 的 SocketIoClientDotNet,它允許 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

程式碼說明

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

一旦成功連接 (Socket.EVENT_CONNECT),我們將打印一條消息,指示我們已連接到伺服器。

然後,我們使用 socket.Emit("message", "Hello from C# client!") 從客戶端向伺服器傳送訊息。 這會向伺服器發送一條內容為「Hello from C# client!」的消息。

接下來,我們通過使用 socket.On("message", (data) => { ...)為 "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
$vbLabelText   $csharpLabel

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

上述代碼的輸出

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

Socket io .NET(開發人員如何運作):圖 6 - 使用 WebSocket URL 的 WebTransport 連接的控制台輸出。

Web Transport 的優勢

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

高效數據傳輸: 它通過利用多路複用流和先進功能提供高效的數據傳輸。

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

多路复用流:支持多路复用流,允许运行多条数据流通过单个连接同时发送和接收。

創新:隨著網頁開發人員不斷採用Web Transport,我們可以期待在網路通信協議方面看到更多的創新。

改進的使用者體驗:採用 Web Transport 可以通過更快速和更可靠的數據傳輸來改善網路上的使用者體驗。

IronPDF 庫介紹

IronPDF 是一個完整的 .NET PDF 庫,專為使用 C# 的開發者設計。 這個強大的工具允許開發人員輕鬆在其應用程式中建立操作閱讀PDF文件。 使用 IronPDF,開發人員可以從HTML 字串HTML 檔案URL生成 PDF 文件,這使其在各種使用情境中非常多功能。 此外,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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

輸出

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。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# foreach 與索引(開發者如何使用)
下一個 >
Junit Java(如何為開發者工作)