跳至页脚内容
.NET 帮助

Socket io .NET(开发者用法)

通过Socket.IO库,服务器能够提供实时、双向和事件驱动的通信。 它广泛用于网络应用程序中,如聊天应用、实时更新和协作平台等任务。 尽管Socket.IO通常与JavaScript关联,它也可以在客户端与C#一起有效地使用。 有时客户端可能是一个网络浏览器。 在本文中,我们将探讨如何在C#环境中设置和使用Socket.IO客户端。 我们将浏览一些基本示例,并总结其优势和潜在用例。

建立Socket.IO连接的方法

Socket.IO连接可以通过不同的低级传输协议建立:

  • HTTP长轮询
  • Web Sockets

  • Web Transport

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应用程序,您需要一个兼容的服务器实现。 其中一个实现是SocketIoClientDotNet用于.NET,它允许Socket.IO客户端从C#应用程序连接到Socket.IO。

首先,安装所需的NuGet包。 您可以通过包管理器控制台或通过将引用添加到项目文件中进行此操作:

Install-Package SocketIoClientDotNet

SocketIoClientDotNet包的截图

Socket io .NET(开发人员如何操作):图3 - 使用NuGet包管理器解决方案的“管理NuGet包”搜索栏中搜索“SocketIoClientDotNet”包名,选择项目并点击安装按钮安装Socket.IO for NET。

执行此命令将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();
        }
    }
}
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("http://localhost:3000")来创建Socket.IO客户端实例,该实例连接到客户端计算机上运行在端口3000的本地服务器。

连接成功后(Socket.EVENT_CONNECT),我们打印一条消息,表明我们已连接到服务器。

然后,我们使用socket.Emit("message", "Hello from C# client!")从客户端向服务器发送消息。 这将消息内容“来自C#客户端的问候”发送到服务器。

接下来,我们通过注册“message”事件的回调来监听来自服务器的消息,使用socket.On("message", (data) => { ...)。 当服务器发送“message”事件时,回调函数被调用,我们将收到的消息打印到控制台。 如果与服务器的连接从客户端断开(Socket.EVENT_DISCONNECT),我们打印一条消息,表明断开连接。

最后,Console.ReadLine()方法保持控制台窗口打开,以便程序在执行后不会立即退出。

这允许我们查看输出,并确保程序不会过早终止。 Socket io .NET(开发人员如何操作):图4 - 示例代码

代码的屏幕截图

HTTP长轮询

长轮询是一种在Web开发中使用的技术,它使用一个库在客户端(通常是Web浏览器)和服务器之间发送消息。

它通过在服务器上触发事件来实现实时通信,客户端可以接收这些事件,而无需持续轮询。 此方法对于需要即时更新的应用程序特别有效,例如聊天应用程序或股票行情。 Socket io .NET(开发人员如何操作):图5 - HTTP长轮询

Socket io .NET (How It Works For Developers): Figure 5 - HTTP长轮询

WebSocket通过在单个TCP连接上建立全双工的通信通道,促进双向通信。

该协议使客户端(通常为Web浏览器)和服务器之间的实时交互成为可能,促进双方异步交换消息。 ### 建立WebSocket通信

客户端发送WebSocket握手请求给服务器,表明其希望建立WebSocket连接。

在收到握手请求后,服务器响应WebSocket握手响应,表明连接已成功建立。 通过WebSocket连接发送的消息可以是任何格式的(例如,文本或二进制),并以异步方式进行发送和接收。 作为一项前沿协议,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 Namespace
$vbLabelText   $csharpLabel

然后,我们在连接上创建一个双向的流,并通过流发送一些数据([1, 2, 3, 4])。 最后,我们从流中读取数据并将其记录到控制台中。 #### 上述代码的输出

当您用WebSocket回声服务器运行应用程序时,输出应该看起来像这样:

Socket io .NET(开发人员如何操作):图6 - 使用WebSocket URL的WebSocket连接的控制台输出。

Web Transport的优势

  • 现代替代方案:Web Transport提供了传统网络通信协议(如TCP和UDP)的现代替代方案。

  • 高效的数据传输:通过利用多路复用流和先进的特性,它提供了高效的数据传输。
  • 高性能:非常适合构建对低延迟和可靠数据传输有极高要求的高性能Web应用程序。
  • 多路复用流:支持多路复用流,同一个连接上可以同时发送和接收多条数据流。
  • 创新:随着Web开发人员继续采用Web Transport,我们可以期待在网络通信协议领域看到更多创新。
  • 改善的用户体验:采用Web Transport可以带来更快和更可靠的数据传输,从而改善网络用户体验。

IronPDF库的介绍

IronPDF是一个多功能的.NET PDF库,专为使用C#的开发人员设计。

该功能强大的工具允许开发人员在其应用程序中轻松读取PDF文件。 This powerful tool allows developers to effortlessly create, manipulate, and read PDF files within their applications. With IronPDF, developers can generate PDF documents from HTML strings, HTML files, and URLs, making it highly versatile for various use cases. 通过NuGet包管理器简化C#项目中的PDF文件处理过程,简化了开发并提高了生产力。 Socket io .NET(开发人员如何操作):图7 - IronPDF for .NET: C# PDF库

在Visual Studio中或者通过命令行使用NuGet包管理器安装IronPDF。

使用 NuGet 包管理器进行安装

在Visual Studio中,进入控制台: - 工具 -> NuGet包管理器 -> 包管理器控制台

IronPDF代码示例

Install-Package IronPdf

下面是一个使用IronPDF将二进制数据转换为PDF文件的简单示例。在Main方法中调用GeneratePDF方法并将数据作为参数传递给此前的示例中的数据:

PDF生成类代码

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

Socket io .NET(开发人员如何操作):图8 - 使用Socket.IO和IronPDF的控制台输出

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

输出

在提供的代码中,IronPDF用于从通过WebSocket连接接收到的十六进制字符串生成PDF文档。

GeneratePDF方法使用许可证密钥初始化IronPDF,并利用其ChromePdfRenderer实例将十六进制字符串作为HTML内容渲染为PDF,使用RenderHtmlAsPdf方法。 您可以在此处获取免费许可证密钥。 此PDF随后通过SaveAs方法本地保存为“Data.pdf”。 IronPDF的整合实现了将动态WebSocket数据无缝转化为结构化PDF格式,展示了其在将实时数据流转化为存档文档方面的实用性。 ### 生成的PDF文件

Socket io .NET(开发人员如何操作):图9 - 使用IronPDF生成的输出PDF

将Socket.IO与C#一起使用为与连接客户端的实时交互带来了许多机会,超出了JavaScript和Node.js的领域。

结论

将Socket.IO和IronPDF等工具集成到您的.NET项目中可以显著增强实时通信和PDF处理能力。 Socket.IO促进了客户端与服务器之间的无缝实时双向通信,而IronPDF为操作PDF文档提供了强大的功能。 Socket.IO facilitates seamless real-time, bidirectional communication between clients and servers, while IronPDF offers robust features for creating and manipulating PDF documents effortlessly.

常见问题解答

如何在C#环境中设置Socket.IO客户端?

要在C#环境中设置Socket.IO客户端,可以使用SocketIoClientDotNet包。这使您的C#应用程序能够与Socket.IO服务器通信,促进实时的双向通信。

在Web应用程序中使用Socket.IO有哪些优势?

Socket.IO提供实时、双向和事件驱动的通信,非常适合需要实时更新的Web应用程序,如聊天应用、协作平台和在线游戏。

我可以在Visual Studio 2022中使用Socket.IO吗?

是的,您可以通过创建控制台项目并安装诸如SocketIoClientDotNet之类的必要软件包,在Visual Studio 2022中使用Socket.IO,以便在您的C#应用程序中实现实时通信。

IronPDF如何增强使用Socket.IO的实时应用程序?

IronPDF可以通过允许开发人员从实时的WebSocket数据生成和操作PDF来增强实时应用程序。这对于从动态数据流创建结构化文档非常有用。

连接C#客户端到Socket.IO服务器的过程是什么?

要连接C#客户端到Socket.IO服务器,您需要使用SocketIoClientDotNet包。这包括设置客户端监听和发送事件,使其能够与服务器进行实时通信。

HTTP长轮询在Socket.IO中如何工作?

HTTP长轮询是Socket.IO使用的一种方法,通过保持请求打开直到服务器响应,以便在新数据可用时立即进行更新,维持持久连接。

WebSocket在Socket.IO通信中扮演什么角色?

WebSocket在Socket.IO通信中扮演关键角色,通过单一的TCP连接实现全双工通信,促进客户端与服务器之间的高效实时数据交换。

如何安装SocketIoClientDotNet包?

您可以使用Visual Studio中的NuGet包管理器安装SocketIoClientDotNet包。打开包管理器控制台并执行命令:Install-Package SocketIoClientDotNet

将IronPDF与Socket.IO集成的用例是什么?

将IronPDF与Socket.IO集成对于需要从动态数据生成PDF的实时应用程序非常有用,例如报告工具、实时数据分析和自动化文档生成系统。

使用Web Transport在Socket.IO中有什么好处?

Web Transport在传统的TCP和UDP上提供了改进的延迟和拥堵控制,支持多路复用流和增强的安全性,适合现代实时通信需求。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。