Zum Fußzeileninhalt springen
.NET HILFE

Supersocket C# Beispiel (Funktionsweise für Entwickler)

Developing a Server-Side Socket Application with SuperSocket and Integrating IronPDF

SuperSocket C# is an excellent framework for developing a server-side socket application, whether you're working on a GPS server or an industrial control system. It supports various network protocol implementations and ensures your socket works efficiently. This lightweight cross-platform framework is designed to be extensible, providing flexibility for different environments. With SuperSocket, you can easily send data between clients and servers, and its source code is available for customization to meet specific project requirements.

It is an open-source framework, so any developer can implement and access it through GitHub.

SuperSocket C# Example (How It Works for Developers): Figure 1 - GitHub page for SuperSocket

IronPDF is a powerful .NET library for creating, editing, and extracting content from PDF documents. It's designed for developers who need to integrate PDF functionality into their applications. IronPDF supports various features like generating PDFs from HTML, merging PDFs, and extracting text and images from PDFs.

SuperSocket and IronPDF together can power complex server-side applications. They offer a wide range of functionalities to meet the needs of modern .NET developers. These libraries are perfect for whether you're building a data acquisition server or a robust game server where real-time chat applications are necessary.

Getting Started with SuperSocket C#

Setting Up SuperSocket C# in .NET Projects

To start using SuperSocket C#, you need to set up your .NET project. First, install the SuperSocket NuGet package. Open your project in Visual Studio and run the following command in the Package Manager Console:

Install-Package SuperSocket

SuperSocket C# Example (How It Works for Developers): Figure 2 - Console output from installing SuperSocket

Once installed, you can configure your server instance. Create a new configuration file named appsettings.json. This file will define the server settings, including the listeners and protocols.

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

Next, create a class to configure the server. This class will read the settings from appsettings.json and initialize the server instance.

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

A Basic SuperSocket C# Example

Let's look at a basic example of a SuperSocket C# application. This example demonstrates how to create a simple echo server that sends back any received data.

First, define the session class. This class will handle the socket connections and manage data communication.

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

Next, configure and run the server with the echo session.

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

This example shows how to create a simple echo server using SuperSocket C#. The server listens for connections and echoes back any data it receives.

Implementing Features of SuperSocket C#

Handling Multiple Listeners

SuperSocket C# supports multiple listeners, allowing your server to handle different protocols and ports. This feature is useful for creating versatile applications like data acquisition servers and GPS servers.

First, update your appsettings.json to include multiple listeners:

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

Next, configure the server to use these listeners:

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

With this setup, your server can handle connections on both ports 4040 and 5050. This capability is crucial for applications that need to manage various network protocols.

Implementing Binary Data Handling

SuperSocket C# is efficient at handling binary data. This is important for applications that require binary-level compatibility, such as industrial control systems.

First, define a session class that processes binary 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);
    }
}
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

Next, configure and run the server with the binary data session:

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

This example demonstrates how to receive and send binary data using SuperSocket C#. It's useful for high-performance applications that need to process binary protocols.

Managing Socket Connections

Maintaining socket connections is essential for ensuring reliable communication. SuperSocket C# simplifies this process.

First, define a session class that manages socket connections:

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

Next, configure and run the server with the connection session:

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

This setup helps manage socket connections, ensuring that your server remains robust and reliable.

Creating a Command-Line Server

SuperSocket C# supports creating command-line servers. This feature is useful for applications that require simple text-based protocols.

First, define a command class that processes text commands:

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

Next, configure the server to use the command:

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

This example shows how to create a simple command-line server using SuperSocket C#. It's ideal for lightweight text-based protocols.

Integrating SuperSocket C# with IronPDF

Integrating IronPDF with SuperSocket in your C# applications can significantly enhance your server capabilities, especially when it comes to handling PDF files. Let's explore how to merge these two powerful libraries effectively.

Introduction to IronPDF

IronPDF webpage

IronPDF .NET Library is a versatile .NET library designed for creating, editing, and extracting content from PDF documents. Whether you need to generate reports, invoices, or any other PDF-based documents, IronPDF provides an easy-to-use API to accomplish these tasks. Its main feature is its HTML-to-PDF Conversion capabilities. It's a great tool for developers looking to incorporate PDF functionality into their applications without dealing with the complexities of PDF specifications.

IronPDF excels in HTML to PDF conversion, ensuring precise preservation of original layouts and styles. It's perfect for creating PDFs from web-based content such as reports, invoices, and documentation. With support for HTML files, URLs, and raw HTML strings, IronPDF easily produces high-quality PDF documents.

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

Use Case of Merging IronPDF with SuperSocket C#

Imagine you have a server built with SuperSocket that needs to handle client requests for generating and sending PDF documents dynamically. By integrating IronPDF, your server can process these requests, create PDFs on the fly, and send them back to the clients seamlessly.

Code Example of Use Case

Here's a complete code example demonstrating how to integrate IronPDF with SuperSocket. This example sets up a simple SuperSocket server that listens for client connections, processes a request to generate a PDF, and sends the generated PDF back to the client.

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

This integration allows you to leverage the powerful features of IronPDF within a SuperSocket server, enabling dynamic PDF generation and efficient client-server communication.

Conclusion

IronPDF licensing information

Integrating SuperSocket with IronPDF's Comprehensive Features is a powerful combination for creating dynamic, high-performance server applications that can handle PDF generation and processing seamlessly. With SuperSocket's robust socket server framework and IronPDF's comprehensive PDF functionalities, you can develop scalable and versatile applications to meet various needs, from data acquisition systems to game servers and industrial control systems.

IronPDF offers a free trial, and its licensing starts from $799, providing excellent value for the extensive capabilities it brings to your development projects. By merging these two libraries, you can streamline your server's ability to handle complex tasks efficiently, enhancing both functionality and performance.

Häufig gestellte Fragen

Wofür wird SuperSocket C# verwendet?

SuperSocket C# wird zur Entwicklung serverseitiger Socket-Anwendungen verwendet. Es ist hochgradig erweiterbar und unterstützt verschiedene Netzwerkprotokolle, was es für Umgebungen wie GPS-Server und industrielle Steuerungssysteme geeignet macht.

Wie kann ich HTML in einer .NET-Anwendung in PDF umwandeln?

Sie können die Methode RenderHtmlAsPdf von IronPDF verwenden, um HTML-Strings in PDFs zu konvertieren, und RenderHtmlFileAsPdf, um HTML-Dateien innerhalb einer .NET-Anwendung in PDFs umzuwandeln.

Wie richtet man einen SuperSocket-Server in einem .NET-Projekt ein?

Um einen SuperSocket-Server in einem .NET-Projekt einzurichten, müssen Sie das SuperSocket NuGet-Paket installieren, den Server mit einer appsettings.json-Datei konfigurieren und den Server innerhalb Ihres Anwendungscodes initialisieren.

Wie kann IronPDF serverseitige Anwendungen verbessern?

IronPDF kann serverseitige Anwendungen verbessern, indem es dynamische PDF-Generierungs- und Verarbeitungsfunktionen bereitstellt, die die Echtzeiterstellung und -verteilung von PDF-Dokumenten basierend auf Kundenanforderungen ermöglichen.

Kann SuperSocket mehrere Protokoll-Listener verwalten?

Ja, SuperSocket kann mehrere Protokoll-Listener verwalten, sodass eine einzelne Serverinstanz verschiedene Protokolle und Ports gleichzeitig für Anwendungen wie Datenerfassungsserver handhaben kann.

Welche Vorteile bietet IronPDF bei der Verarbeitung von PDF-Dokumenten?

IronPDF bietet umfassende Funktionen zur Erstellung, Bearbeitung und Extraktion von Inhalten aus PDF-Dokumenten. Es ist ideal für Anwendungen, die eine fortgeschrittene Verarbeitung und Manipulation von PDF-Dokumenten erfordern.

Wie handhabt SuperSocket gleichzeitige Socket-Verbindungen?

SuperSocket behandelt gleichzeitige Socket-Verbindungen mit Sitzungs-Klassen zur Verwaltung von Verbindungsvorgängen und gewährleistet so eine zuverlässige Kommunikation und solide Serverleistung, selbst unter hoher Last.

Ist es möglich, PDF-Funktionalitäten in SuperSocket-Anwendungen zu integrieren?

Ja, durch die Integration von IronPDF in Ihre SuperSocket-Anwendungen können Sie PDF-Funktionalitäten wie die dynamische PDF-Erstellung und -Bearbeitung hinzufügen, die die Fähigkeiten der Anwendung verbessern.

Was sind häufige Anwendungsfälle für SuperSocket?

Häufige Anwendungsfälle für SuperSocket sind GPS-Server, industrielle Steuerungssysteme, Datenerfassungsserver und Echtzeitspieleserver, die alle von einer effizienten und zuverlässigen Socket-Kommunikation profitieren.

Wie kann ich Binärdaten in SuperSocket verarbeiten?

SuperSocket verarbeitet Binärdaten effizient, indem es Sitzungs-Klassen verwendet, um eingehende Binärpakete zu verarbeiten und Antworten zu senden, was für Anwendungen, die eine Verarbeitung auf Binärebene erfordern, unerlässlich ist.

Unterstützt IronPDF die HTML-zu-PDF-Konvertierung in Serveranwendungen?

Ja, IronPDF unterstützt die HTML-zu-PDF-Konvertierung in Serveranwendungen und ermöglicht die nahtlose Umwandlung von HTML-Inhalten in hochwertige PDF-Dokumente.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen