.NET 帮助

Supersocket C# 示例(它如何为开发者工作)

发布 2024年七月1日
分享:

利用 SuperSocket 开发服务器端套接字应用程序并集成 IronPDF

超级套接字 C# 是开发服务器端套接字应用程序的绝佳框架,无论您是在开发 GPS 服务器还是工业控制系统。它支持各种网络协议实现,确保您的套接字高效运行。这个轻量级跨平台框架具有可扩展性,可为不同环境提供灵活性。有了 SuperSocket,您可以轻松地在客户端和服务器之间发送数据,它的源代码可供定制,以满足特定项目的要求。

它是一个开源框架,因此任何开发人员都可以通过 GitHub 实现和访问它。

SuperSocket C# 示例(开发人员如何使用):图 1 - 超级套接字的 GitHub 页面

IronPDF 是一个功能强大的 .NET 库,用于创建、编辑和提取 PDF 文档中的内容。它专为需要将 PDF 功能集成到应用程序中的开发人员而设计。IronPDF 支持多种功能,如从 HTML 生成 PDF、合并 PDF 以及从 PDF 中提取文本和图像。

SuperSocket 和 IronPDF 可共同支持复杂的服务器端应用程序。它们提供了广泛的功能,可满足现代 .NET 开发人员的需求。无论您是要构建数据采集服务器还是需要实时聊天应用程序的强大游戏服务器,这些库都是您的理想选择。

超级套接字 C# 入门

在 .NET 项目中设置超级套接字 C

要开始使用 SuperSocket C#,您需要设置您的 .NET 项目。首先,安装 SuperSocket NuGet 软件包。在 Visual Studio 中打开项目,在软件包管理器控制台中运行以下命令:

Install-Package SuperSocket

SuperSocket C# 示例(面向开发人员的工作原理):图 2 - 安装超级套接字后的控制台输出

安装完成后,就可以配置服务器实例了。创建一个名为 appsettings.json 的新配置文件。该文件将定义服务器设置,包括侦听器和协议。

{
  "serverOptions": {
    "name": "SuperSocketServer",
    "listeners": [
      {
        "ip": "Any",
        "port": 4040
      }
    ]
  }
}

接下来,创建一个用于配置服务器的类。该类将从 appsettings.json 中读取设置并初始化服务器实例。

public class ServerConfig
{
    public async Task Configure()
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<YourSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
public class ServerConfig
{
    public async Task Configure()
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<YourSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
Public Class ServerConfig
	Public Async Function Configure() As Task
		Dim host = SuperSocketHostBuilder.Create().UseTcpServer().UseSession(Of YourSession)().ConfigureAppConfiguration(Sub(hostCtx, configApp)
				configApp.AddJsonFile("appsettings.json", [optional]:= False, reloadOnChange:= True)
		End Sub).Build()
		Await host.RunAsync()
	End Function
End Class
VB   C#

基本超级套接字 C# 示例

让我们来看一个超级套接字 C# 应用程序的基本示例。该示例演示了如何创建一个简单的回声服务器,并将接收到的数据发送回来。

首先,定义会话类。该类将处理套接字连接并管理数据通信。

public class EchoSession : AppSession
{
    protected override async ValueTask OnSessionStartedAsync()
    {
        await base.OnSessionStartedAsync();
        Console.WriteLine("New session started.");
    }
    protected override async ValueTask OnSessionClosedAsync(CloseEventArgs e)
    {
        await base.OnSessionClosedAsync(e);
        Console.WriteLine("Session closed.");
    }
    protected override async ValueTask OnPackageReceivedAsync(ReadOnlyMemory<byte> package)
    {
        await SendAsync(package);
    }
}
public class EchoSession : AppSession
{
    protected override async ValueTask OnSessionStartedAsync()
    {
        await base.OnSessionStartedAsync();
        Console.WriteLine("New session started.");
    }
    protected override async ValueTask OnSessionClosedAsync(CloseEventArgs e)
    {
        await base.OnSessionClosedAsync(e);
        Console.WriteLine("Session closed.");
    }
    protected override async ValueTask OnPackageReceivedAsync(ReadOnlyMemory<byte> package)
    {
        await SendAsync(package);
    }
}
Public Class EchoSession
	Inherits AppSession

	Protected Overrides Async Function OnSessionStartedAsync() As ValueTask
		Await MyBase.OnSessionStartedAsync()
		Console.WriteLine("New session started.")
	End Function
	Protected Overrides Async Function OnSessionClosedAsync(ByVal e As CloseEventArgs) As ValueTask
		Await MyBase.OnSessionClosedAsync(e)
		Console.WriteLine("Session closed.")
	End Function
	Protected Overrides Async Function OnPackageReceivedAsync(ByVal package As ReadOnlyMemory(Of Byte)) As ValueTask
		Await SendAsync(package)
	End Function
End Class
VB   C#

接下来,配置并运行带有 echo 会话的服务器。

public class EchoServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<EchoSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
public class EchoServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<EchoSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
Public Class EchoServer
	Public Shared Async Function Main(ByVal args() As String) As Task
		Dim host = SuperSocketHostBuilder.Create().UseTcpServer().UseSession(Of EchoSession)().ConfigureAppConfiguration(Sub(hostCtx, configApp)
				configApp.AddJsonFile("appsettings.json", [optional]:= False, reloadOnChange:= True)
		End Sub).Build()
		Await host.RunAsync()
	End Function
End Class
VB   C#

本例演示如何使用 SuperSocket C# 创建一个简单的回声服务器。服务器会监听连接,并回传接收到的任何数据。

实现 C# 超级套接字的功能

处理多个监听器

SuperSocket C# 支持多监听器,允许服务器处理不同的协议和端口。该功能对于创建数据采集服务器和 GPS 服务器等多功能应用程序非常有用。

首先,更新 appsettings.json 以包含多个监听器:

{
  "serverOptions": {
    "name": "MultiListenerServer",
    "listeners": [
      {
        "ip": "Any",
        "port": 4040
      },
      {
        "ip": "Any",
        "port": 5050
      }
    ]
  }
}

接下来,配置服务器以使用这些监听器:

public class MultiListenerServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<YourSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
public class MultiListenerServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<YourSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
Public Class MultiListenerServer
	Public Shared Async Function Main(ByVal args() As String) As Task
		Dim host = SuperSocketHostBuilder.Create().UseTcpServer().UseSession(Of YourSession)().ConfigureAppConfiguration(Sub(hostCtx, configApp)
				configApp.AddJsonFile("appsettings.json", [optional]:= False, reloadOnChange:= True)
		End Sub).Build()
		Await host.RunAsync()
	End Function
End Class
VB   C#

通过这种设置,服务器可以处理 4040 和 5050 端口的连接。这种能力对于需要管理各种网络协议的应用程序来说至关重要。

实现二进制数据处理

SuperSocket C# 可高效处理二进制数据。这对于需要二进制级别兼容性的应用程序(如工业控制系统)来说非常重要。

首先,定义一个处理二进制数据的会话类:

public class BinaryDataSession : AppSession
{
    protected override async ValueTask OnPackageReceivedAsync(ReadOnlyMemory<byte> package)
    {
        var data = package.ToArray();
        Console.WriteLine("Received binary data: " + BitConverter.ToString(data));
        await SendAsync(data);
    }
}
public class BinaryDataSession : AppSession
{
    protected override async ValueTask OnPackageReceivedAsync(ReadOnlyMemory<byte> package)
    {
        var data = package.ToArray();
        Console.WriteLine("Received binary data: " + BitConverter.ToString(data));
        await SendAsync(data);
    }
}
Public Class BinaryDataSession
	Inherits AppSession

	Protected Overrides Async Function OnPackageReceivedAsync(ByVal package As ReadOnlyMemory(Of Byte)) As ValueTask
		Dim data = package.ToArray()
		Console.WriteLine("Received binary data: " & BitConverter.ToString(data))
		Await SendAsync(data)
	End Function
End Class
VB   C#

接下来,使用二进制数据会话配置并运行服务器:

public class BinaryDataServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<BinaryDataSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
public class BinaryDataServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<BinaryDataSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
Public Class BinaryDataServer
	Public Shared Async Function Main(ByVal args() As String) As Task
		Dim host = SuperSocketHostBuilder.Create().UseTcpServer().UseSession(Of BinaryDataSession)().ConfigureAppConfiguration(Sub(hostCtx, configApp)
				configApp.AddJsonFile("appsettings.json", [optional]:= False, reloadOnChange:= True)
		End Sub).Build()
		Await host.RunAsync()
	End Function
End Class
VB   C#

本示例演示了如何使用 SuperSocket C# 接收和发送二进制数据。它适用于需要处理二进制协议的高性能应用程序。

管理套接字连接

维护套接字连接对于确保可靠通信至关重要。SuperSocket C# 简化了这一过程。

首先,定义一个会话类来管理套接字连接:

public class ConnectionSession : AppSession
{
    protected override async ValueTask OnSessionStartedAsync()
    {
        await base.OnSessionStartedAsync();
        Console.WriteLine("Connection started.");
    }
    protected override async ValueTask OnSessionClosedAsync(CloseEventArgs e)
    {
        await base.OnSessionClosedAsync(e);
        Console.WriteLine("Connection closed.");
    }
    protected override async ValueTask OnPackageReceivedAsync(ReadOnlyMemory<byte> package)
    {
        await SendAsync(package);
    }
}
public class ConnectionSession : AppSession
{
    protected override async ValueTask OnSessionStartedAsync()
    {
        await base.OnSessionStartedAsync();
        Console.WriteLine("Connection started.");
    }
    protected override async ValueTask OnSessionClosedAsync(CloseEventArgs e)
    {
        await base.OnSessionClosedAsync(e);
        Console.WriteLine("Connection closed.");
    }
    protected override async ValueTask OnPackageReceivedAsync(ReadOnlyMemory<byte> package)
    {
        await SendAsync(package);
    }
}
Public Class ConnectionSession
	Inherits AppSession

	Protected Overrides Async Function OnSessionStartedAsync() As ValueTask
		Await MyBase.OnSessionStartedAsync()
		Console.WriteLine("Connection started.")
	End Function
	Protected Overrides Async Function OnSessionClosedAsync(ByVal e As CloseEventArgs) As ValueTask
		Await MyBase.OnSessionClosedAsync(e)
		Console.WriteLine("Connection closed.")
	End Function
	Protected Overrides Async Function OnPackageReceivedAsync(ByVal package As ReadOnlyMemory(Of Byte)) As ValueTask
		Await SendAsync(package)
	End Function
End Class
VB   C#

接下来,配置并运行带有连接会话的服务器:

public class ConnectionServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<ConnectionSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
public class ConnectionServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<ConnectionSession>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
Public Class ConnectionServer
	Public Shared Async Function Main(ByVal args() As String) As Task
		Dim host = SuperSocketHostBuilder.Create().UseTcpServer().UseSession(Of ConnectionSession)().ConfigureAppConfiguration(Sub(hostCtx, configApp)
				configApp.AddJsonFile("appsettings.json", [optional]:= False, reloadOnChange:= True)
		End Sub).Build()
		Await host.RunAsync()
	End Function
End Class
VB   C#

这种设置有助于管理套接字连接,确保服务器保持稳健可靠。

创建命令行服务器

SuperSocket C# 支持创建命令行服务器。这一功能对于需要简单文本协议的应用程序非常有用。

首先,定义一个处理文本命令的命令类:

public class MyCommand : IAsyncCommand<AppSession, StringPackageInfo>
{
    public async ValueTask ExecuteAsync(AppSession session, StringPackageInfo package)
    {
        var commandKey = package.Key;
        var parameters = package.Parameters;
        await session.SendAsync(Encoding.UTF8.GetBytes($"You said: {string.Join(' ', parameters)}"));
    }
}
public class MyCommand : IAsyncCommand<AppSession, StringPackageInfo>
{
    public async ValueTask ExecuteAsync(AppSession session, StringPackageInfo package)
    {
        var commandKey = package.Key;
        var parameters = package.Parameters;
        await session.SendAsync(Encoding.UTF8.GetBytes($"You said: {string.Join(' ', parameters)}"));
    }
}
Public Class MyCommand
	Implements IAsyncCommand(Of AppSession, StringPackageInfo)

	Public Async Function ExecuteAsync(ByVal session As AppSession, ByVal package As StringPackageInfo) As ValueTask
		Dim commandKey = package.Key
		Dim parameters = package.Parameters
		Await session.SendAsync(Encoding.UTF8.GetBytes($"You said: {String.Join(" "c, parameters)}"))
	End Function
End Class
VB   C#

接下来,配置服务器以使用该命令:

public class CommandLineServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<AppSession>()
            .UseCommand<StringPackageParser>()
            .AddCommand<MyCommand>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
public class CommandLineServer
{
    public static async Task Main(string[] args)
    {
        var host = SuperSocketHostBuilder.Create()
            .UseTcpServer()
            .UseSession<AppSession>()
            .UseCommand<StringPackageParser>()
            .AddCommand<MyCommand>()
            .ConfigureAppConfiguration((hostCtx, configApp) =>
            {
                configApp.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            })
            .Build();
        await host.RunAsync();
    }
}
Public Class CommandLineServer
	Public Shared Async Function Main(ByVal args() As String) As Task
		Dim host = SuperSocketHostBuilder.Create().UseTcpServer().UseSession(Of AppSession)().UseCommand(Of StringPackageParser)().AddCommand(Of MyCommand)().ConfigureAppConfiguration(Sub(hostCtx, configApp)
				configApp.AddJsonFile("appsettings.json", [optional]:= False, reloadOnChange:= True)
		End Sub).Build()
		Await host.RunAsync()
	End Function
End Class
VB   C#

本示例展示了如何使用 SuperSocket C# 创建一个简单的命令行服务器。它是基于文本的轻量级协议的理想选择。

将 SuperSocket C# 与 IronPDF 集成

在 C# 应用程序中将 IronPDF 与 SuperSocket 集成,可以大大增强服务器功能,尤其是在处理 PDF 文件时。让我们来探讨如何有效地合并这两个功能强大的库。

IronPDF 简介

SuperSocket C# 示例(面向开发人员的工作原理):图 3 - IronPDF 网页

IronPDF IronPDF 是一个通用的 .NET 库,设计用于创建、编辑和提取 PDF 文档中的内容。无论您是需要生成报告、发票还是其他任何基于 PDF 的文档,IronPDF 都能提供一个易于使用的 API 来完成这些任务。其主要特点是 HTML 脚本转换为 PDF 文档** 功能。对于希望将 PDF 功能集成到其应用程序中的开发人员来说,这是一个非常好的工具,无需处理复杂的 PDF 规范。

将 IronPDF 与 SuperSocket C# 合并的用例

想象一下,您有一个使用 SuperSocket 构建的服务器,需要处理客户端动态生成和发送 PDF 文档的请求。通过集成 IronPDF,您的服务器可以处理这些请求,在运行中创建 PDF,并将其无缝地发送回客户端。

用例代码示例

下面是一个完整的代码示例,演示了如何将 IronPDF 与 SuperSocket 集成。该示例设置了一个简单的 SuperSocket 服务器,用于监听客户端连接、处理生成 PDF 的请求并将生成的 PDF 发送回客户端。

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using IronPdf;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;

namespace SuperSocketIronPDFExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var appServer = new AppServer();
            var serverConfig = new ServerConfig
            {
                Name = "SuperSocketServer",
                Ip = "Any",
                Port = 2012,
                Mode = SocketMode.Tcp,
                MaxConnectionNumber = 100,
            };
            if (!appServer.Setup(serverConfig))
            {
                Console.WriteLine("Failed to set up!");
                return;
            }
            appServer.NewSessionConnected += NewSessionConnected;
            appServer.NewRequestReceived += NewRequestReceived;
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                return;
            }
            Console.WriteLine("Server is running. Press any key to stop...");
            Console.ReadKey();
            appServer.Stop();
        }

        private static void NewSessionConnected(AppSession session)
        {
            Console.WriteLine($"New session connected: {session.SessionID}");
        }

        private static void NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
        {
            if (requestInfo.Key == "GENPDF")
            {
                var pdfDocument = CreatePdfDocument(requestInfo.Body);
                var pdfBytes = pdfDocument.BinaryData;
                session.Send(pdfBytes, 0, pdfBytes.Length);
                Console.WriteLine("PDF document sent to client.");
            }
        }

        private static PdfDocument CreatePdfDocument(string content)
        {
            var pdfRenderer = new ChromePdfRenderer();
            var pdfDocument = pdfRenderer.RenderHtmlAsPdf(content);
            return pdfDocument;
        }
    }

    public class AppServer : AppServer<AppSession, StringRequestInfo>
    {
    }

    public class AppSession : AppSession<AppSession, StringRequestInfo>
    {
    }

    public class StringRequestFilterFactory : IRequestFilterFactory<StringRequestInfo>
    {
        public IRequestFilter<StringRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, IPEndPoint remoteEndPoint)
        {
            return new TerminatorRequestFilterFactory().CreateFilter(appServer, appSession, remoteEndPoint);
        }
    }
}
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using IronPdf;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;

namespace SuperSocketIronPDFExample
{
    class Program
    {
        static void Main(string[] args)
        {
            var appServer = new AppServer();
            var serverConfig = new ServerConfig
            {
                Name = "SuperSocketServer",
                Ip = "Any",
                Port = 2012,
                Mode = SocketMode.Tcp,
                MaxConnectionNumber = 100,
            };
            if (!appServer.Setup(serverConfig))
            {
                Console.WriteLine("Failed to set up!");
                return;
            }
            appServer.NewSessionConnected += NewSessionConnected;
            appServer.NewRequestReceived += NewRequestReceived;
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                return;
            }
            Console.WriteLine("Server is running. Press any key to stop...");
            Console.ReadKey();
            appServer.Stop();
        }

        private static void NewSessionConnected(AppSession session)
        {
            Console.WriteLine($"New session connected: {session.SessionID}");
        }

        private static void NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
        {
            if (requestInfo.Key == "GENPDF")
            {
                var pdfDocument = CreatePdfDocument(requestInfo.Body);
                var pdfBytes = pdfDocument.BinaryData;
                session.Send(pdfBytes, 0, pdfBytes.Length);
                Console.WriteLine("PDF document sent to client.");
            }
        }

        private static PdfDocument CreatePdfDocument(string content)
        {
            var pdfRenderer = new ChromePdfRenderer();
            var pdfDocument = pdfRenderer.RenderHtmlAsPdf(content);
            return pdfDocument;
        }
    }

    public class AppServer : AppServer<AppSession, StringRequestInfo>
    {
    }

    public class AppSession : AppSession<AppSession, StringRequestInfo>
    {
    }

    public class StringRequestFilterFactory : IRequestFilterFactory<StringRequestInfo>
    {
        public IRequestFilter<StringRequestInfo> CreateFilter(IAppServer appServer, IAppSession appSession, IPEndPoint remoteEndPoint)
        {
            return new TerminatorRequestFilterFactory().CreateFilter(appServer, appSession, remoteEndPoint);
        }
    }
}
Imports System
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading.Tasks
Imports IronPdf
Imports SuperSocket.SocketBase
Imports SuperSocket.SocketBase.Protocol

Namespace SuperSocketIronPDFExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			Dim appServer As New AppServer()
			Dim serverConfig As New ServerConfig With {
				.Name = "SuperSocketServer",
				.Ip = "Any",
				.Port = 2012,
				.Mode = SocketMode.Tcp,
				.MaxConnectionNumber = 100
			}
			If Not appServer.Setup(serverConfig) Then
				Console.WriteLine("Failed to set up!")
				Return
			End If
			AddHandler appServer.NewSessionConnected, AddressOf NewSessionConnected
			AddHandler appServer.NewRequestReceived, AddressOf NewRequestReceived
			If Not appServer.Start() Then
				Console.WriteLine("Failed to start!")
				Return
			End If
			Console.WriteLine("Server is running. Press any key to stop...")
			Console.ReadKey()
			appServer.Stop()
		End Sub

		Private Shared Sub NewSessionConnected(ByVal session As AppSession)
			Console.WriteLine($"New session connected: {session.SessionID}")
		End Sub

		Private Shared Sub NewRequestReceived(ByVal session As AppSession, ByVal requestInfo As StringRequestInfo)
			If requestInfo.Key = "GENPDF" Then
				Dim pdfDocument = CreatePdfDocument(requestInfo.Body)
				Dim pdfBytes = pdfDocument.BinaryData
				session.Send(pdfBytes, 0, pdfBytes.Length)
				Console.WriteLine("PDF document sent to client.")
			End If
		End Sub

		Private Shared Function CreatePdfDocument(ByVal content As String) As PdfDocument
			Dim pdfRenderer = New ChromePdfRenderer()
			Dim pdfDocument = pdfRenderer.RenderHtmlAsPdf(content)
			Return pdfDocument
		End Function
	End Class

	Public Class AppServer
		Inherits AppServer(Of AppSession, StringRequestInfo)

	End Class

	Public Class AppSession
		Inherits AppSession(Of AppSession, StringRequestInfo)

	End Class

	Public Class StringRequestFilterFactory
		Implements IRequestFilterFactory(Of StringRequestInfo)

		Public Function CreateFilter(ByVal appServer As IAppServer, ByVal appSession As IAppSession, ByVal remoteEndPoint As IPEndPoint) As IRequestFilter(Of StringRequestInfo)
			Return (New TerminatorRequestFilterFactory()).CreateFilter(appServer, appSession, remoteEndPoint)
		End Function
	End Class
End Namespace
VB   C#

通过这种集成,您可以在 SuperSocket 服务器中利用 IronPDF 的强大功能,实现动态 PDF 生成和高效的客户端-服务器通信。

结论

SuperSocket C# 示例(面向开发人员的工作原理):图 4 - IronPDF 许可页面

将超级插座与 IronPDF SuperSocket 和 IronPDF 是一个强大的组合,可以创建动态、高性能的服务器应用程序,无缝地处理 PDF 生成和处理。利用 SuperSocket 强大的套接字服务器框架和 IronPDF 全面的 PDF 功能,您可以开发可扩展的多功能应用程序,满足从数据采集系统到游戏服务器和工业控制系统的各种需求。

IronPDF 提供 免费试用它的许可起价为 749 美元,为您的开发项目带来了丰富的功能,具有极高的性价比。通过合并这两个库,您可以简化服务器高效处理复杂任务的能力,增强功能和性能。

< 前一页
Quartz .NET(它对开发人员的工作原理)
下一步 >
Dottrace .NET Core(它是如何为开发人员工作的)

准备开始了吗? 版本: 2024.10 刚刚发布

免费NuGet下载 总下载量: 11,108,738 查看许可证 >