跳過到頁腳內容
.NET幫助

Supersocket C# 示例(對於開發者的運行原理)

使用SuperSocket開發伺服器端Socket應用程式並集成IronPDF

SuperSocket C# 是一個優秀的框架,用於開發伺服器端的Socket應用程式,無論是在開發GPS伺服器或工業控制系統。 它支持各種網路協議的實現,確保您的Socket高效運行。 這個輕量的跨平台框架設計成可擴展,提供不同環境的靈活性。 使用SuperSocket,您可以輕鬆在客戶端和伺服器之間傳送數據,並且其源代碼可根據具體項目需求進行定制。

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

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

IronPDF 是一個強大的.NET庫,用於創建、編輯和提取PDF文件中的內容。 它是為需要在其應用程式中集成PDF功能的開發人員設計的。 IronPDF支持多種功能,如從HTML生成PDF、合並PDF,以及從PDF中提取文本和圖像。

SuperSocket和IronPDF一起可以驅動複雜的伺服器端應用程式。 它們提供廣泛的功能來滿足現代.NET開發人員的需求。 無論您是在構建數據採集伺服器還是需要即時聊天應用的健壯遊戲伺服器,這些庫都很合適。

開始使用SuperSocket C

在.NET項目中設置SuperSocket C

要開始使用SuperSocket C#,您需要設置您的.NET項目。 首先,安裝SuperSocket NuGet包。 在Visual Studio中打開您的項目,並在 Package Manager 控制台中執行以下命令:

Install-Package SuperSocket

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

安裝完成後,您可以配置您的伺服器實例。 創建一個名為appsettings.json的新配置文件。 此文件將定義伺服器設置,包括監聽器和協議。

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

接下來,創建一個類來配置伺服器。 此類將從appsettings.json中讀取設置並初始化伺服器實例。

using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
Imports Microsoft.Extensions.Configuration
Imports SuperSocket
Imports SuperSocket.Server

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

一個基本的SuperSocket C#範例

讓我們來看看一個SuperSocket C#應用程式的基本範例。 此範例演示如何創建一個簡單的回聲伺服器來返回任何收到的數據。

首先,定義會話類。 此類將處理Socket連接和管理數據通信。

using SuperSocket;

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);
    }
}
using SuperSocket;

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);
    }
}
Imports SuperSocket

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

接下來,配置並運行具有回聲功能的伺服器。

using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
Imports Microsoft.Extensions.Configuration
Imports SuperSocket
Imports SuperSocket.Server

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

此範例顯示如何使用SuperSocket C#創建一個簡單的回聲伺服器。 伺服器監聽連接並回應它接收到的任何數據。

實現SuperSocket C#的功能

處理多個監聽器

SuperSocket C#支持多個監聽器,允許您的伺服器處理不同的協議和端口。 此功能對於創建如數據採集伺服器和GPS伺服器等多功能應用程式很有用。

首先,更新您的appsettings.json以包括多個監聽器:

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

接下來,配置伺服器以使用這些監聽器:

using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
Imports Microsoft.Extensions.Configuration
Imports SuperSocket
Imports SuperSocket.Server

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

通過此配置,您的伺服器可以在端口4040和5050上處理連接。此功能對於需要管理各種網路協議的應用程式至關重要。

實現二進制數據處理

SuperSocket C#在處理二進制數據方面非常高效。 這對於需要二進制級別兼容性的應用程式,如工業控制系統,非常重要。

首先,定義一個處理二進制數據的會話類:

using System;
using SuperSocket;

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);
    }
}
using System;
using SuperSocket;

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);
    }
}
Imports System
Imports SuperSocket

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

接下來,配置並運行具有二進制數據會話的伺服器:

using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
Imports Microsoft.Extensions.Configuration
Imports SuperSocket
Imports SuperSocket.Server

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

此範例演示如何使用SuperSocket C#接收和發送二進制數據。 它對於需要處理二進制協議的高性能應用程式非常有用。

管理Socket連接

維持Socket連接對於確保可靠的通信至關重要。 SuperSocket C#簡化了此過程。

首先,定義一個管理Socket連接的會話類:

using SuperSocket;

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);
    }
}
using SuperSocket;

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);
    }
}
Imports SuperSocket

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

接下來,配置並運行具有連接會話的伺服器:

using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Server;

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();
    }
}
Imports Microsoft.Extensions.Configuration
Imports SuperSocket
Imports SuperSocket.Server

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

此配置有助於管理Socket連接,確保您的伺服器保持健壯和可靠。

創建命令行伺服器

SuperSocket C#支持創建命令行伺服器。 此功能對於需要簡單文本協議的應用程式非常有用。

首先,定義一個處理文本命令的命令類:

using System.Text;
using System.Threading.Tasks;
using SuperSocket.Command;
using SuperSocket.ProtoBase;

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)}"));
    }
}
using System.Text;
using System.Threading.Tasks;
using SuperSocket.Command;
using SuperSocket.ProtoBase;

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)}"));
    }
}
Imports System.Text
Imports System.Threading.Tasks
Imports SuperSocket.Command
Imports SuperSocket.ProtoBase

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

接下來,配置伺服器以使用該命令:

using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Command;
using SuperSocket.ProtoBase;
using SuperSocket.Server;

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();
    }
}
using Microsoft.Extensions.Configuration;
using SuperSocket;
using SuperSocket.Command;
using SuperSocket.ProtoBase;
using SuperSocket.Server;

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();
    }
}
Imports Microsoft.Extensions.Configuration
Imports SuperSocket
Imports SuperSocket.Command
Imports SuperSocket.ProtoBase
Imports SuperSocket.Server

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

此範例顯示如何使用SuperSocket C#創建一個簡單的命令行伺服器。 它非常適合輕量級文本協議。

Integrating SuperSocket C# with IronPDF

在您的C#應用程式中將IronPDF與SuperSocket集成可以顯著提高您的伺服器功能,特別是在處理PDF文件時。 讓我們探討如何有效地合並這兩個強大的庫。

IronPDF 介紹

IronPDF網頁

IronPDF .NET庫是設計用於從PDF文件創建、編輯和提取內容的多功能.NET庫。 無論您需要生成報告、發票或任何其他基於PDF的文件,IronPDF提供了一個易於使用的API來完成這些任務。 其主要功能是其HTML轉PDF轉換能力。 這是一個很好的工具,讓開發人員可以將PDF功能合併到其應用程式中而不用處理PDF規範的複雜性。

IronPDF 在HTML 到 PDF轉換方麵表現出色,確保準確保持原始佈局和樣式。 它非常適合從網路內容生成 PDF,如報告、發票和文檔。 支持 HTML 文件、URL 和原始 HTML 字串的 IronPDF 可以輕鬆生成高質量的 PDF 文檔。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

將IronPDF與SuperSocket C#合併的用例

假設您有一個使用SuperSocket構建的伺服器,需要動態處理客戶端請求以生成和發送PDF文件。 通過集成IronPDF,您的伺服器可以處理這些請求,即時生成PDF並無縫地將其發送回客戶端。

用例的代碼範例

這裡有一個完整的代碼範例,演示如何將IronPDF與SuperSocket集成。 此範例設置了一個簡單的SuperSocket伺服器,該伺服器監聽客戶端連接,處理生成PDF的請求,並將生成的PDF返回給客戶端。

using System;
using System.Net;
using System.Text;
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 SuperSocket.SocketBase.Config.ServerConfig
            {
                Name = "SuperSocketServer",
                Ip = "Any",
                Port = 2012,
                Mode = SuperSocket.SocketBase.SocketMode.Tcp,
                MaxConnectionNumber = 100,
            };

            if (!appServer.Setup(serverConfig))
            {
                Console.WriteLine("Failed to set up!");
                return;
            }

            appServer.NewSessionConnected += NewSessionConnected;
            appServer.NewRequestReceived += (session, 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.");
                }
            };

            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 PdfDocument CreatePdfDocument(string content)
        {
            var pdfRenderer = new ChromePdfRenderer();
            var pdfDocument = pdfRenderer.RenderHtmlAsPdf(content);
            return pdfDocument;
        }

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

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

    public class AppSession : AppSession<AppSession, StringRequestInfo>
    {
    }
}
using System;
using System.Net;
using System.Text;
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 SuperSocket.SocketBase.Config.ServerConfig
            {
                Name = "SuperSocketServer",
                Ip = "Any",
                Port = 2012,
                Mode = SuperSocket.SocketBase.SocketMode.Tcp,
                MaxConnectionNumber = 100,
            };

            if (!appServer.Setup(serverConfig))
            {
                Console.WriteLine("Failed to set up!");
                return;
            }

            appServer.NewSessionConnected += NewSessionConnected;
            appServer.NewRequestReceived += (session, 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.");
                }
            };

            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 PdfDocument CreatePdfDocument(string content)
        {
            var pdfRenderer = new ChromePdfRenderer();
            var pdfDocument = pdfRenderer.RenderHtmlAsPdf(content);
            return pdfDocument;
        }

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

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

    public class AppSession : AppSession<AppSession, StringRequestInfo>
    {
    }
}
Imports System
Imports System.Net
Imports System.Text
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 = New SuperSocket.SocketBase.Config.ServerConfig With {
				.Name = "SuperSocketServer",
				.Ip = "Any",
				.Port = 2012,
				.Mode = SuperSocket.SocketBase.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, Sub(session, requestInfo)
				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

			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 Function CreatePdfDocument(ByVal content As String) As PdfDocument
			Dim pdfRenderer = New ChromePdfRenderer()
			Dim pdfDocument = pdfRenderer.RenderHtmlAsPdf(content)
			Return pdfDocument
		End Function

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

	Public Class AppServer
		Inherits AppServer(Of AppSession, StringRequestInfo)

	End Class

	Public Class AppSession
		Inherits AppSession(Of AppSession, StringRequestInfo)

	End Class
End Namespace
$vbLabelText   $csharpLabel

此集成使您能夠利用IronPDF的強大功能,實現在SuperSocket伺服器內的動態PDF生成和高效的客戶端伺服器通信。

結論

IronPDF許可信息

將SuperSocket與IronPDF的全面功能集成是創建動態、高性能伺服器應用程式的強大組合,可以無縫處理PDF生成和處理。 憑藉SuperSocket穩健的Socket伺服器框架和IronPDF全面的PDF功能,您可以開發可擴展且多功能的應用程式,以滿足各種需求,從數據採集系統到遊戲伺服器和工業控制系統。

IronPDF提供免費試用,其許可證從$799開始,為您的開發項目帶來豐富功能,提供出色的價值。 通過合併這兩個庫,您可以簡化伺服器處理複雜任務的能力,有效提升功能性和性能。

常見問題解答

SuperSocket C# 的用途是什麼?

SuperSocket C# 用於開發伺服器端的 Socket 應用程式。因其高度可擴展性及支持多種網路協議,使其適合於 GPS 伺服器和工業控制系統等環境。

如何在 .NET 應用程序中將 HTML 轉換為 PDF?

你可以使用 IronPDF 的 RenderHtmlAsPdf 方法來將 HTML 字串轉換為 PDF,使用 RenderHtmlFileAsPdf 來將 HTML 文件轉換為 PDF,這些功能可以在 .NET 應用程式中使用。

如何在 .NET 專案中設置 SuperSocket 伺服器?

要在 .NET 專案中設置 SuperSocket 伺服器,你需要安裝 SuperSocket 的 NuGet 套件,使用 appsettings.json 文件進行伺服器配置,並在應用程式代碼中初始化伺服器。

IronPDF 如何增強伺服器端應用程式?

IronPDF 能夠增強伺服器端應用程式,通過提供動態 PDF 生成和處理功能,實現根據客戶端請求的實時 PDF 文檔創建和分發。

SuperSocket 能否管理多個協議監聽器?

可以,SuperSocket 可以管理多個協議監聽器,允許單一伺服器實例同時處理多種協議和端口,適合於像數據採集伺服器這樣的應用程式。

IronPDF 在 PDF 文檔處理方面具備哪些優勢?

IronPDF 提供了完善的 PDF 文檔創建、編輯和內容提取功能。適合於需要高級 PDF 文檔處理和操作的應用程式。

SuperSocket 如何處理並發的 Socket 連接?

SuperSocket 使用會話類來管理連接事件,確保在高負載下也能實現可靠的通信和穩定的伺服器性能。

是否可以將 PDF 功能集成到 SuperSocket 應用程式中?

可以,通過將 IronPDF 集成到你的 SuperSocket 應用程式中,可以增加 PDF 功能,如動態 PDF 生成和編輯,從而提升應用程式的能力。

SuperSocket 的常見用例有哪些?

SuperSocket 的常見用例包括 GPS 伺服器、工業控制系統、數據採集伺服器以及實時遊戲伺服器,這些應用受益於高效和可靠的 Socket 通信。

我如何在 SuperSocket 中處理二進制數據?

SuperSocket 通過利用會話類來高效地處理二進制數據包並發送響應,這對於需要二進制層次數據處理的應用程式來說是必不可少的。

IronPDF 支持在伺服器應用程式中進行 HTML 到 PDF 的轉換嗎?

是的,IronPDF 支持在伺服器應用中進行 HTML 到 PDF 的轉換,無縫地將 HTML 內容轉換為高質量的 PDF 文檔。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。