在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
這Socket.IO伺服器作為一個強大的庫,促進實時、雙向和事件驅動的通信。 它廣泛用於網路應用程式中,如聊天應用程式、實時更新和協作平台等任務。 雖然 Socket.IO 通常與 JavaScript 相關聯,但它也可以在用戶端使用 C# 有效運作。 有時候,客戶端可能是一個網頁瀏覽器。 在本文中,我們將探討如何在 C# 環境中設置和使用 Socket.IO 客戶端。 我們將介紹一些基本範例,最後總結其優勢和潛在的使用案例。
這Socket.IO可以使用不同的低層傳輸建立連接:
Web Sockets
打開 Visual Studio,然後在起始窗口中選擇 建立新專案。
要在 Visual Studio 2022 中建立主控台應用程式,啟動 Visual Studio 並從開始視窗中選擇「建立新專案」。 選擇「控制台應用程式」範本,使用名稱和位置配置專案,並確保選擇 .NET 6.0。
Socket.IOJavaScript 庫,使網路客戶端和伺服器能夠進行即時通信。 它由兩部分組成:
在 .NET 應用程式中使用 Socket.IO 以Visual Studio,您需要一個兼容的伺服器實作。 其中一個實現是SocketIoClientDotNet for .NET,允許一個Socket IO客戶端從C#應用程式連接到Socket.IO。
首先,安裝所需的 NuGet 套件。 您可以透過套件管理員主控台或將引用添加到您的專案文件來完成此操作。
Install-Package SocketIoClientDotNet
Install-Package SocketIoClientDotNet
執行此命令將把 Socket.IO 客戶端庫整合到您的 .NET 專案中,使您的 C# 應用程式能夠連接到 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();
}
}
}
在這個片段中,我們首先通過調用 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()方法保持控制台窗口開啟,以便程式在執行後不會立即退出。 這讓我們能夠查看輸出並確保程式不會過早終止。
長輪詢是一種用於網頁開發的技術,使用庫在客戶端之間發送消息。(通常是網頁瀏覽器)和伺服器。 它能夠透過在伺服器上觸發事件實現實時通信,這些事件可以被客戶端接收而無需持續輪詢。 此方法對於需要即時更新的應用程式特別有用,例如聊天應用程式或股票行情顯示器。
WebSocket 透過在單一 TCP 連線上建立全雙工通訊通道,以促進雙向通訊。 此協議允許客戶端(通常是網頁瀏覽器)與伺服器之間進行即時互動,使雙方能夠異步交換消息。
客戶端向服務器發送 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));
}
}
}
}
在此範例中,我們首先使用 WebSocket URL 建立到伺服器的新 WebTransport 連接。(wss://echo.websocket.org). 然後,我們在連接上建立一個雙向流並發送一些數據。([1, 2, 3, 4])在溪流上方。 最後,我們從流中讀取數據並記錄到控制台。
當您使用 WebSocket 回音伺服器運行應用程式時,輸出應類似如下所示:
現代替代方案: Web Transport 提供了一種傳統 web 通訊協議(如 TCP 和 UDP)的現代替代方案。
高效資料傳輸: 它通過利用多路傳輸流和進階特性來提供高效的資料傳輸。
高性能: 非常適合構建需要低延遲和可靠數據傳輸的高性能網絡應用程序。
多路復用流: 支持多路復用流,允許多個數據流在單一連接上同時發送和接收。
創新: 隨著網頁開發人員持續採用 Web Transport,我們可以預期看到更多在網頁通訊協議上的創新。
改進的用戶體驗: 採用 Web Transport 可以提高網站使用者的體驗,因為其資料傳輸速度更快且更可靠。
IronPDF是一個專為使用C#的開發人員設計的全面.NET PDF庫。 這個強大的工具讓開發者能夠輕鬆地建立, 操作,和讀取在其應用程式中使用 PDF 文件。 使用 IronPDF,開發人員可以從HTML 字串, HTML 文件,和網址,使其在各種使用情境中具有高度的靈活性。 此外,IronPDF 提供了高級 PDF 編輯功能,如添加標頭、頁尾、水印等。 通過 NuGet 套件管理器無縫整合到 C# 項目中,簡化了 PDF 文件的處理過程,精簡開發流程並提高生產力。
使用 NuGet 套件管理器在 Visual Studio 或從命令列安裝 IronPDF。 在 Visual Studio 中,進入控制台:
Install-Package IronPdf
Install-Package 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);
}
}
}
}
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}");
}
}
}
在提供的程式碼中,IronPDF 用於從透過 WebSocket 連線收到的十六進位字串生成 PDF 文件。 GeneratePDF 方法使用授權金鑰初始化 IronPDF,並使用其 ChromePdfRenderer 實例通過 RenderHtmlAsPdf 方法將十六進位字串作為 HTML 內容渲染成 PDF。 您可以從以下位置獲取免費授權密鑰這裡. 然後使用 SaveAs 方法將此 PDF 本地儲存為「Data.pdf」。 IronPDF 的整合可以將動態 WebSocket 數據無縫轉換為結構化 PDF 格式,展示了其在將實時數據流轉換為存檔文檔方面的實用性。
利用Socket.IO使用C#為與連接客戶端的即時互動提供了眾多機會,不僅僅局限於JavaScript和Node.js的領域。 集成像Socket.IO和IronPDF到您的 .NET 專案中,可以顯著增強即時通訊和 PDF 處理能力。 Socket.IO 促進了客戶端和伺服器之間流暢的即時雙向通信,而 IronPDF 提供強大的功能用於創建和操作輕鬆處理 PDF 文件。
IronPDF釋放其全部潛力,確保在您的 C# 應用程序中高效且可靠地生成和操作 PDF。