.NET 幫助

Supersocket C# 範例(開發人員如何使用)

發佈 2024年7月1日
分享:

使用 SuperSocket 開發伺服器端 Socket 應用程式並整合 IronPDF

SuperSocket C#是一個出色的框架,用於開發伺服器端的套接字應用程序,無論您正在開發 GPS 伺服器還是工業控制系統。 它支持多種網路協議實作,確保您的套接字高效運作。 這個輕量級跨平台框架設計為可擴展的,提供了對不同環境的靈活性。 使用 SuperSocket,您可以輕鬆地在客戶端和服務器之間傳輸數據,其源代碼可供定制以滿足特定項目的需求。

這是一個開源框架,因此任何開發者都可以通過 GitHub 實施和訪問。

SuperSocket C#範例(開發人員如何運作):圖1 - SuperSocket的GitHub頁面

IronPDF是一個用於建立、編輯和從 PDF 文件中提取內容的強大 .NET 庫。 它是為需要將 PDF 功能整合到其應用程式中的開發人員而設計的。 IronPDF 支援多種功能,例如從 HTML 生成 PDF、合併 PDF,以及從 PDF 提取文字和圖像。

SuperSocket 和 IronPDF 可以共同驅動複雜的伺服器端應用程式。 他們提供廣泛的功能來滿足現代 .NET 開發者的需求。 這些程式庫非常適合用於建立數據採集伺服器或需要即時聊天應用的強大遊戲伺服器。

開始使用 SuperSocket C

在 .NET 專案中設置 SuperSocket C

要開始使用 SuperSocket C#,您需要設置您的 .NET 專案。 首先,安裝 SuperSocket NuGet 套件。 在 Visual Studio 中打開您的專案,然後在套件管理器主控台中執行以下命令:

Install-Package SuperSocket

SuperSocket C# 範例 (開發者如何使用):圖 2 - 安裝 SuperSocket 後的控制台輸出

安裝完成後,您可以配置伺服器實例。 創建一個名為 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#

基本的 SuperSocket C# 範例

讓我們看看一個 SuperSocket C# 應用程式的基本範例。 此範例展示如何建立一個簡單的回音伺服器,將收到的任何資料傳回。

首先,定義 session 類別。 此類別將處理套接字連接並管理數據通信。

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#

接下來,配置並運行帶有回聲會話的伺服器。

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# 建立一個簡單的回聲伺服器。 伺服器會監聽連線並回應任何接收到的數據。

實現 SuperSocket 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 集成

將IronPDF與SuperSocket整合到您的C#應用程式中,可以顯著增強您的伺服器功能,尤其是在處理PDF檔案時。 讓我們來探索如何有效地合併這兩個強大的函式庫。

IronPDF 介紹

IronPDF 網頁

IronPDF .NET Library是一個多功能的.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 生成和高效的客戶端-伺服器通信。

結論

IronPDF 授權資訊

將 SuperSocket 與集成IronPDF 的全面特點是一個強大的組合,用於創建動態、高效能的伺服器應用程式,可以無縫處理 PDF 的生成和處理。 使用SuperSocket強大的套接字伺服器框架和IronPDF全面的PDF功能,您可以開發出可擴展且多功能的應用程式,以滿足各種需求,從數據獲取系統到遊戲伺服器以及工業控制系統。

IronPDF 提供一個免費試用其授權費用從 $749 起,為您的開發項目帶來廣泛功能,提供極佳的價值。 通過合併這兩個庫,您可以有效簡化服務器處理複雜任務的能力,從而增強功能性和性能。

< 上一頁
Quartz .NET(它如何為開發人員工作)
下一個 >
Dottrace .NET Core(對開發人員的作用)

準備開始了嗎? 版本: 2024.12 剛剛發布

免費 NuGet 下載 總下載次數: 11,622,374 查看許可證 >