Socket io .NET(对开发人员的工作原理)
通过Socket.IO库,服务器能够提供实时、双向和事件驱动的通信。 它广泛用于网络应用程序中,如聊天应用、实时更新和协作平台等任务。 尽管Socket.IO通常与JavaScript关联,它也可以在客户端与C#一起有效地使用。 有时客户端可能是一个网络浏览器。 在本文中,我们将探讨如何在C#环境中设置和使用Socket.IO客户端。 我们将浏览一些基本示例,并总结其优势和潜在用例。
建立Socket.IO连接的方法
Socket.IO连接可以通过不同的低级传输方式建立:
-
HTTP长轮询
-
Web Sockets
-
Web Transport

在Visual Studio 2022中创建控制台项目
打开Visual Studio,并在起始窗口中选择创建新项目。
要在Visual Studio 2022中创建控制台应用程序,请启动Visual Studio并从起始窗口选择"创建新项目"。 选择"控制台应用"模板,配置项目名称和位置,并确保选择.NET 6.0。
什么是Socket.IO?
Socket.IO是一个JavaScript库,能够使网页客户端与服务器进行实时通信。 它由两个部分组成:
Socket IO的部分
- 客户端库:在浏览器中运行。
- 服务器端库:在Node.js上运行。
安装必要的包
要在Visual Studio中使用Socket.IO进行.NET应用程序,您需要一个兼容的服务器实现。 其中一个实现是 SocketIoClientDotNet,用于.NET,允许Socket.IO客户端从C#应用程序连接到Socket.IO。
首先,安装所需的NuGet包。 您可以通过包管理器控制台或通过将引用添加到项目文件中进行此操作:
SocketIoClientDotNet包的截图

执行此命令将Socket.IO客户端库集成到您的.NET项目中,增强您的C#应用程序与Socket.IO服务器连接,促进用户与系统之间的通信。
创建Socket.IO
在深入研究C#客户端之前,让我们使用.NET Core的控制台应用在Visual Studio中设置一个基本的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();
}
}
}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 NamespaceImports 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代码解释
在代码片段中,我们首先通过调用IO.Socket("http://localhost:3000")创建一个Socket.IO客户端实例,该实例连接到客户端机器上运行的3000端口的本地服务器。
成功连接(Socket.EVENT_CONNECT)后,我们打印一条消息,指示已连接至服务器。
然后,我们使用socket.Emit("message", "Hello from C# client!")从客户端向服务器发送一条消息。 这条消息内容为"来自C#客户端的问候!"发送到服务器。
接下来,我们通过注册"message"事件的回调来监听来自服务器的消息,使用socket.On("message", (data) => { ... )。 })`。 当服务器发送"消息"事件时,回调函数被调用,我们将接收到的消息打印到控制台。
如果从客户端断开与服务器的连接(Socket.EVENT_DISCONNECT),我们打印一条消息,指示连接已断开。
最后,Console.ReadLine()方法保持控制台窗口打开,以便程序在执行完后不会立即退出。 这使我们能够看到输出,并确保程序不会过早终止。
代码的屏幕截图

HTTP 长轮询
长轮询是一种在Web开发中使用的技术,它使用一个库在客户端(通常是Web浏览器)和服务器之间发送消息。
它通过在服务器上触发事件来实现实时通信,客户端可以接收这些事件,而无需持续轮询。 此方法对于需要即时更新的应用程序特别有效,例如聊天应用程序或股票行情。 该方法特别适用于需要即时更新的应用程序,例如聊天应用程序或股票行情。

Web Sockets
WebSocket通过在单个TCP连接上建立全双工的通信通道,促进双向通信。
该协议使客户端(通常为Web浏览器)和服务器之间的实时交互成为可能,促进双方异步交换消息。
建立 WebSocket 通信
在收到握手请求后,服务器响应WebSocket握手响应,表明连接已成功建立。 通过WebSocket连接发送的消息可以是任何格式的(例如,文本或二进制),并以异步方式进行发送和接收。
Web Transport
作为一项前沿协议,Web Transport引入了额外的特性,以增强网络通信,超越像TCP和UDP这样的传统协议的限制。通过利用UDP和QUIC,它解决了其前身的缺点,使其更加用户友好和高效。
作为一项前沿协议,Web Transport引入了额外的特性,以增强网络通信,超越像TCP和UDP这样的传统协议的限制。通过利用UDP和QUIC,它解决了其前身的缺点,使其更加用户友好和高效。
对于用户而言,这意味着降低延迟和改进拥塞控制,最终提供更顺畅和响应迅速的网络体验。 此外,Web Transport提供了更好的安全措施,确保数据传输比TCP更加安全。在这些进步中,Web Transport减少了耗时的数据传输步骤,优化了客户端和服务器的整体性能。 以下是Web Transport在Web应用程序中的一个基本示例:
在这个示例中,我们首先使用WebSocket URL (wss://echo.websocket.org)创建一个新的WebSocket 连接到服务器。
using System;
using System.Net.WebSockets;
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.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.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 NamespaceImports System
Imports System.Net.WebSockets
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在此示例中,我们首先使用WebSocket URL(wss://echo.websocket.org)创建与服务器的新WebSocket连接。 然后,我们在连接上创建一个双向流,并通过该流发送一些数据([1, 2, 3, 4])。 最后,我们从流中读取数据并将其记录到控制台。
上述代码的输出
当您使用 WebSocket 回声服务器运行应用程序时,输出应该类似于:

Web Transport 的优势
-
现代替代方案:Web Transport提供了传统网络通信协议(如TCP和UDP)的现代替代方案。
-
高效的数据传输:通过利用多路复用流和先进的特性,它提供了高效的数据传输。
-
高性能:非常适合构建对低延迟和可靠数据传输有极高要求的高性能Web应用程序。
-
多路复用流:支持多路复用流,同一个连接上可以同时发送和接收多条数据流。
-
创新:随着Web开发人员继续采用Web Transport,我们可以期待在网络通信协议领域看到更多创新。
-
改善的用户体验:采用Web Transport可以带来更快和更可靠的数据传输,从而改善网络用户体验。
-
改进的用户体验:采用 Web 传输可以由于更快和更可靠的数据传输而改善网页上的用户体验。
IronPDF 库简介
IronPDF是一个多功能的.NET PDF库,专为使用C#的开发人员设计。
该功能强大的工具允许开发人员在其应用程序中轻松创建、操作和读取PDF文件。 使用IronPDF,开发人员可以从HTML字符串、HTML文件和URL生成PDF文档,使其在各种用途中显得高度灵活。 使用IronPDF,开发者可以从 HTML字符串、HTML文件 和 URLs 生成PDF文档,使其在各种用例中具有高度的灵活性。 通过NuGet包管理器简化C#项目中的PDF文件处理过程,简化了开发并提高了生产力。 

使用 NuGet 包管理器进行安装
在Visual Studio中,进入控制台: 在 Visual Studio 中,转到控制台:
IronPDF代码示例
下面是一个使用IronPDF将二进制数据转换为PDF文件的简单示例。在Main方法中调用GeneratePDF方法并将数据作为参数传递给此前的示例中的数据:
这是一个使用IronPDF将二进制数据转换为PDF文件的简单示例。在GeneratePDF方法,并将数据作为参数传递,如上例中所示:
using System;
using System.Net.WebSockets;
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.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.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 NamespaceImports System
Imports System.Net.WebSockets
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 NamespacePDF 生成类代码
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($"<h1>Received Data</h1><p>{data}</p>");
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($"<h1>Received Data</h1><p>{data}</p>");
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($"<h1>Received Data</h1><p>{data}</p>")
Dim filePath As String = "Data.pdf"
pdf.SaveAs(filePath)
Console.WriteLine($"PDF Generation Completed. File Saved as {filePath}")
End Sub
End Class
End NamespaceImports 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($"<h1>Received Data</h1><p>{data}</p>")
Dim filePath As String = "Data.pdf"
pdf.SaveAs(filePath)
Console.WriteLine($"PDF Generation Completed. File Saved as {filePath}")
End Sub
End Class
End Namespace输出

GeneratePDF方法使用许可证密钥初始化IronPDF,并利用其ChromePdfRenderer实例将十六进制字符串作为HTML内容渲染为PDF,使用RenderHtmlAsPdf方法。 RenderHtmlAsPdf方法将十六进制字符串作为HTML内容渲染为PDF。 此PDF随后通过SaveAs方法本地保存为"Data.pdf"。 然后,这个PDF使用SaveAs方法本地保存为"Data.pdf"。
生成的 PDF 文件

结论
using Socket.IO 和 C# 介绍了与连接客户端实时交互的众多机会,超越了 JavaScript 和 Node.js 的领域。 将像 Socket.IO 和 IronPDF 这样的工具集成到您的 .NET 项目中,可以显著提升实时通信和 PDF 处理能力。 Socket.IO 可促进客户端和服务器之间的无缝实时双向通信,而 IronPDF 则为轻松创建和操作PDF 文档提供了强大的功能。
Jacob Mellor是Iron Software的首席技术官,也是C# PDF技术的先锋工程师。作为Iron Software核心代码库的原始开发者,自公司成立以来,他就一直在塑造公司的产品架构,与首席执行官Cameron Rimington一起将其转型为拥有50多人、服务于NASA、特斯拉和全球政府机构的公司。