透かしなしで本番環境でテストしてください。
必要な場所で動作します。
30日間、完全に機能する製品をご利用いただけます。
数分で稼働させることができます。
製品トライアル期間中にサポートエンジニアリングチームへの完全アクセス
Socket.IO サーバーは、リアルタイムで双方向かつイベント駆動の通信を促進する、強力なライブラリとして存在します。 それは、チャットアプリケーション、ライブアップデート、共同プラットフォームなどのタスクのためにウェブアプリケーションで広く使用されています。 Socket.IOは通常JavaScriptと関連付けられていますが、クライアント側でC#と共に効果的に使用することもできます。 時々、クライアントはウェブブラウザであることがあります。 この記事では、C#環境でSocket.IOクライアントを設定し使用する方法を探ります。 基本的な例をいくつか見ていき、利点と潜在的な使用例で締めくくります。
Socket.IOの接続は、さまざまな低レベルのトランスポートで確立できます。
Web Sockets
Visual Studio を開き、スタート ウィンドウで新しいプロジェクトを作成を選択します。
Visual Studio 2022でコンソールアプリケーションを作成するには、Visual Studioを起動し、スタートウィンドウで「新しいプロジェクトの作成」を選択します。 「Console App」テンプレートを選択し、プロジェクトに名前と場所を設定して、.NET 6.0が選択されていることを確認してください。
Socket.IOは、JavaScriptライブラリであり、ウェブクライアントとサーバーがリアルタイム通信を行うことを可能にします。 それは二つの部分で構成されています。
Visual Studioで.NETアプリケーションにSocket.IOを使用するには、互換性のあるサーバー実装が必要です。 そのような実装の一つとして、SocketIoClientDotNet for .NETがあります。これは、C#アプリケーションからSocket IOクライアントがSocket.IOに接続することを可能にします。
まず、必要なNuGetパッケージをインストールします。 パッケージマネージャーコンソールを介して、またはプロジェクトファイルに参照を追加することによってこれを行うことができます。
Install-Package SocketIoClientDotNet
Install-Package SocketIoClientDotNet
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package SocketIoClientDotNet
このコマンドを実行すると、Socket.IOクライアントライブラリが.NETプロジェクトに組み込まれ、C#アプリケーションがSocket.IOサーバーに接続できるようになり、ユーザーとシステム間の通信を促進します。
C#クライアントに入る前に、Visual Studioで.NET Coreコンソールアプリを使用してSocket IOの基本的な例を設定しましょう。 これはクライアントの実装をテストするのに役立ちます。
以下のコードは、C#で書かれた基本的なSocket.IOサーバーを設定し、ポート3000でクライアントの接続を待ち受けます。クライアントがメッセージを送信すると、そのメッセージをログに記録し、受領を確認してクライアントに返信します。
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;
namespace DemoApp
{
internal class Program
{
static void Main(string[] args)
{
// Connect to the Socket.IO server
var socket = IO.Socket("http://localhost:3000");
// Listen for the "connect" event
socket.On(Socket.EVENT_CONNECT, () =>
{
Console.WriteLine("Connected to the server!");
// Emit a message to the server
socket.Emit("message", "Hello from C# client!");
// Listen for messages from the server
socket.On("message", (data) =>
{
Console.WriteLine("Message from server: " + data);
});
});
// Listen for the "disconnect" event
socket.On(Socket.EVENT_DISCONNECT, () =>
{
Console.WriteLine("Disconnected from the server!");
});
// Keep the console window open
Console.ReadLine();
}
}
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Quobject.SocketIoClientDotNet.Client;
namespace DemoApp
{
internal class Program
{
static void Main(string[] args)
{
// Connect to the Socket.IO server
var socket = IO.Socket("http://localhost:3000");
// Listen for the "connect" event
socket.On(Socket.EVENT_CONNECT, () =>
{
Console.WriteLine("Connected to the server!");
// Emit a message to the server
socket.Emit("message", "Hello from C# client!");
// Listen for messages from the server
socket.On("message", (data) =>
{
Console.WriteLine("Message from server: " + data);
});
});
// Listen for the "disconnect" event
socket.On(Socket.EVENT_DISCONNECT, () =>
{
Console.WriteLine("Disconnected from the server!");
});
// Keep the console window open
Console.ReadLine();
}
}
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Imports Quobject.SocketIoClientDotNet.Client
Namespace DemoApp
Friend Class Program
Shared Sub Main(ByVal args() As String)
' Connect to the Socket.IO server
Dim socket = IO.Socket("http://localhost:3000")
' Listen for the "connect" event
socket.On(Socket.EVENT_CONNECT, Sub()
Console.WriteLine("Connected to the server!")
' Emit a message to the server
socket.Emit("message", "Hello from C# client!")
' Listen for messages from the server
socket.On("message", Sub(data)
Console.WriteLine("Message from server: " & data)
End Sub)
End Sub)
' Listen for the "disconnect" event
socket.On(Socket.EVENT_DISCONNECT, Sub()
Console.WriteLine("Disconnected from the server!")
End Sub)
' Keep the console window open
Console.ReadLine()
End Sub
End Class
End Namespace
スニペットでは、IO.Socket("https://localhost:3000") を呼び出して Socket.IO クライアント インスタンス/送信者を最初に作成します。これにより、クライアントマシン上でポート 3000 で実行されているローカルサーバーに接続します。
接続に成功すると(Socket.EVENT_CONNECT)、サーバーに接続されたことを示すメッセージを表示します。
次に、クライアントからサーバーにメッセージを送信するために、ソケットを使用してsocket.Emit("message", "Hello from C# client!")を実行します。 これは、コンテンツ「Hello from C# client!」をサーバーに送信するメッセージです。
次に、socket.On("message", (data) => { ... }). サーバーが「message」イベントを送信すると、コールバック関数が呼び出され、受信したメッセージがコンソールに表示されます。
クライアントからサーバーへの接続が切断された場合(Socket.EVENT_DISCONNECT)、切断を示すメッセージを出力します。
最後に、Console.ReadLine() メソッドは、プログラムが実行後すぐに終了しないようにコンソールウィンドウを開いたままにします。 これにより出力を確認することができ、プログラムが早期に終了しないことを保証します。
ロングポーリングはウェブ開発で使用される技術であり、クライアント(通常はウェブブラウザー)とサーバー間でメッセージを送信するためにライブラリを使用します。 サーバー上でイベントをトリガーし、クライアントが連続ポーリングすることなく受信できるようにすることで、リアルタイム通信を可能にします。 この方法は、チャットアプリケーションや株価ティッカーのように即時更新を必要とするアプリケーションに特に有用です。
WebSocketは単一のTCP接続を介して双方向通信を容易にし、全二重通信チャネルを確立します。 このプロトコルは、クライアント(通常はウェブブラウザ)とサーバーとの間でリアルタイムの相互作用を可能にし、両者が非同期でメッセージを交換することを可能にします。
クライアントはWebSocket接続を確立したいという意図を示して、サーバーにWebSocketハンドシェイクリクエストを送信します。 ハンドシェイクリクエストを受信すると、サーバーはWebSocketハンドシェイク応答で応答し、接続が正常に確立されたことを示します。 WebSocket接続を介して送信されるメッセージは、任意の形式(例えば、テキストまたはバイナリ)であり、非同期に送信および受信できます。
Web Transportは、最先端のプロトコルとして、TCPやUDPのような従来のプロトコルの限界を超えてウェブコミュニケーションを強化するための追加機能を導入します。UDPとQUICを活用することにより、従来のプロトコルの欠点を克服し、よりユーザーフレンドリーで効率的です。 これにより、ユーザーにとって遅延が減少し、輻輳制御が向上し、最終的にはよりスムーズで応答性の高いウェブ体験を提供します。 さらに、Web Transportはより優れたセキュリティ対策を提供し、TCPと比較してより安全なデータ伝送を保証します。これらの進歩により、Web Transportはデータ転送の時間がかかる側面を軽減し、クライアントとサーバーの全体的なパフォーマンスを最適化します。
以下は、WebアプリケーションでWeb Transportを使用する基本的な例です。
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo
{
class Program
{
static async Task Main(string[] args)
{
// The WebSocket URI
string uri = "wss://echo.websocket.org";
// Creating a new WebSocket connection
using (ClientWebSocket webSocket = new ClientWebSocket())
{
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
Console.WriteLine("Connected to the server");
// Sending data over the WebSocket
byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
Console.WriteLine("Data sent to the server");
// Receiving data from the WebSocket
byte[] receiveBuffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
byte[] data = new byte[result.Count];
Array.Copy(receiveBuffer, data, result.Count);
Console.WriteLine("Received data: " + BitConverter.ToString(data));
}
}
}
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo
{
class Program
{
static async Task Main(string[] args)
{
// The WebSocket URI
string uri = "wss://echo.websocket.org";
// Creating a new WebSocket connection
using (ClientWebSocket webSocket = new ClientWebSocket())
{
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
Console.WriteLine("Connected to the server");
// Sending data over the WebSocket
byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
Console.WriteLine("Data sent to the server");
// Receiving data from the WebSocket
byte[] receiveBuffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
byte[] data = new byte[result.Count];
Array.Copy(receiveBuffer, data, result.Count);
Console.WriteLine("Received data: " + BitConverter.ToString(data));
}
}
}
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Namespace SocketIO.Demo
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' The WebSocket URI
Dim uri As String = "wss://echo.websocket.org"
' Creating a new WebSocket connection
Using webSocket As New ClientWebSocket()
Await webSocket.ConnectAsync(New Uri(uri), CancellationToken.None)
Console.WriteLine("Connected to the server")
' Sending data over the WebSocket
Dim sendBuffer() As Byte = { 1, 2, 3, 4 }
Await webSocket.SendAsync(New ArraySegment(Of Byte)(sendBuffer), WebSocketMessageType.Binary, True, CancellationToken.None)
Console.WriteLine("Data sent to the server")
' Receiving data from the WebSocket
Dim receiveBuffer(1023) As Byte
Dim result As WebSocketReceiveResult = Await webSocket.ReceiveAsync(New ArraySegment(Of Byte)(receiveBuffer), CancellationToken.None)
Dim data(result.Count - 1) As Byte
Array.Copy(receiveBuffer, data, result.Count)
Console.WriteLine("Received data: " & BitConverter.ToString(data))
End Using
End Function
End Class
End Namespace
この例では、まず WebSocket URL (wss://echo.websocket.org) を使用してサーバーに新しいWebTransport**接続を作成します。 次に、接続を介して双方向ストリームを作成し、いくつかのデータ([1, 2, 3, 4]**)をそのストリームで送信します。 最後に、ストリームからデータを読み取り、コンソールにログを記録します。
WebSocketエコーサーバーでアプリケーションを実行すると、出力は次のようになります。
現代的な代替: Web Transportは、TCPやUDPなどの従来のウェブ通信プロトコルに対する現代的な代替手段を提供します。
効率的なデータ転送: 複合ストリームと高度な機能を活用して、効率的なデータ転送を実現します。
高性能: 低遅延と信頼性の高いデータ転送を求める高性能なウェブアプリケーションの構築に適しています。
多重化されたストリーム: 1つの接続で複数のデータストリームを同時に送受信できる多重化ストリームをサポートします。
イノベーション: Web開発者がWeb Transportを引き続き採用するにつれて、Web通信プロトコルでのさらなるイノベーションが期待されます。
向上したユーザーエクスペリエンス: Web Transportの採用により、より高速で信頼性の高いデータ転送が可能になり、ウェブ上でのユーザーエクスペリエンスが向上します。
IronPDF は、C#を使用する開発者向けに特別に設計された包括的な.NET PDFライブラリです。 この強力なツールにより、開発者はアプリケーション内でPDFファイルを簡単に作成、操作、および読み取ることができます。 IronPDF を使用すると、開発者は HTML 文字列、HTML ファイル、URL から PDF ドキュメントを生成でき、さまざまなユースケースに対して非常に柔軟性があります。 さらに、IronPDFはヘッダー、フッター、透かしなどを追加する高度なPDF編集機能を提供しています。 そのシームレスなC#プロジェクトへの統合は、NuGetパッケージマネージャーを介してPDFファイルを扱うプロセスを簡素化し、開発を合理化し、生産性を向上させます。
Visual StudioでIronPDFをインストールするか、コマンドラインからNuGetパッケージマネージャーを使用してインストールします。 Visual Studioでコンソールに移動します:
Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
こちらはIronPDFを使用してビットデータをPDFファイルに変換する簡単な例です。MainメソッドでGeneratePDFメソッドを呼び出し、上記の例で使用したデータをパラメータとして渡します。
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo
{
class Program
{
static async Task Main(string[] args)
{
// The WebSocket URI
string uri = "wss://echo.websocket.org";
// Creating a new WebSocket connection
using (ClientWebSocket webSocket = new ClientWebSocket())
{
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
Console.WriteLine("Connected to the server");
// Sending data over the WebSocket
byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
Console.WriteLine("Data sent to the server");
// Receiving data from the WebSocket
byte[] receiveBuffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
byte[] data = new byte[result.Count];
Array.Copy(receiveBuffer, data, result.Count);
Console.WriteLine("Received data: " + BitConverter.ToString(data));
// Data to Generate in PDF File
string pdfData = BitConverter.ToString(data);
PDFGenerator.GeneratePDF(pdfData);
}
}
}
}
using System;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SocketIO.Demo
{
class Program
{
static async Task Main(string[] args)
{
// The WebSocket URI
string uri = "wss://echo.websocket.org";
// Creating a new WebSocket connection
using (ClientWebSocket webSocket = new ClientWebSocket())
{
await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
Console.WriteLine("Connected to the server");
// Sending data over the WebSocket
byte[] sendBuffer = new byte[] { 1, 2, 3, 4 };
await webSocket.SendAsync(new ArraySegment<byte>(sendBuffer), WebSocketMessageType.Binary, true, CancellationToken.None);
Console.WriteLine("Data sent to the server");
// Receiving data from the WebSocket
byte[] receiveBuffer = new byte[1024];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None);
byte[] data = new byte[result.Count];
Array.Copy(receiveBuffer, data, result.Count);
Console.WriteLine("Received data: " + BitConverter.ToString(data));
// Data to Generate in PDF File
string pdfData = BitConverter.ToString(data);
PDFGenerator.GeneratePDF(pdfData);
}
}
}
}
Imports System
Imports System.Net.WebSockets
Imports System.Text
Imports System.Threading
Imports System.Threading.Tasks
Namespace SocketIO.Demo
Friend Class Program
Shared Async Function Main(ByVal args() As String) As Task
' The WebSocket URI
Dim uri As String = "wss://echo.websocket.org"
' Creating a new WebSocket connection
Using webSocket As New ClientWebSocket()
Await webSocket.ConnectAsync(New Uri(uri), CancellationToken.None)
Console.WriteLine("Connected to the server")
' Sending data over the WebSocket
Dim sendBuffer() As Byte = { 1, 2, 3, 4 }
Await webSocket.SendAsync(New ArraySegment(Of Byte)(sendBuffer), WebSocketMessageType.Binary, True, CancellationToken.None)
Console.WriteLine("Data sent to the server")
' Receiving data from the WebSocket
Dim receiveBuffer(1023) As Byte
Dim result As WebSocketReceiveResult = Await webSocket.ReceiveAsync(New ArraySegment(Of Byte)(receiveBuffer), CancellationToken.None)
Dim data(result.Count - 1) As Byte
Array.Copy(receiveBuffer, data, result.Count)
Console.WriteLine("Received data: " & BitConverter.ToString(data))
' Data to Generate in PDF File
Dim pdfData As String = BitConverter.ToString(data)
PDFGenerator.GeneratePDF(pdfData)
End Using
End Function
End Class
End Namespace
using IronPdf;
namespace SocketIO.Demo
{
public class PDFGenerator
{
public static void GeneratePDF(string data)
{
IronPdf.License.LicenseKey = "Your-Licence-Key-Here";
Console.WriteLine("PDF Generating Started...");
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
Console.WriteLine("PDF Processing ....");
var pdf = renderer.RenderHtmlAsPdf(data);
string filePath = "Data.pdf";
pdf.SaveAs(filePath);
Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}");
}
}
}
using IronPdf;
namespace SocketIO.Demo
{
public class PDFGenerator
{
public static void GeneratePDF(string data)
{
IronPdf.License.LicenseKey = "Your-Licence-Key-Here";
Console.WriteLine("PDF Generating Started...");
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
Console.WriteLine("PDF Processing ....");
var pdf = renderer.RenderHtmlAsPdf(data);
string filePath = "Data.pdf";
pdf.SaveAs(filePath);
Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}");
}
}
}
Imports IronPdf
Namespace SocketIO.Demo
Public Class PDFGenerator
Public Shared Sub GeneratePDF(ByVal data As String)
IronPdf.License.LicenseKey = "Your-Licence-Key-Here"
Console.WriteLine("PDF Generating Started...")
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
Console.WriteLine("PDF Processing ....")
Dim pdf = renderer.RenderHtmlAsPdf(data)
Dim filePath As String = "Data.pdf"
pdf.SaveAs(filePath)
Console.WriteLine($"PDF Generation Completed,File Saved as ${filePath}")
End Sub
End Class
End Namespace
提供されたコードでは、IronPDF を使用して、WebSocket接続を通じて受け取った16進文字列からPDFドキュメントを生成します。 GeneratePDF メソッドは、ライセンスキーで IronPDF を初期化し、その ChromePdfRenderer インスタンスを使用して、RenderHtmlAsPdf メソッドを通じて 16 進文字列を HTML コンテンツとして PDF にレンダリングします。 無料ライセンスキーはこちらから取得できます。 このPDFは、その後、SaveAsメソッドを使用してローカルに「Data.pdf」として保存されます。 IronPDFの統合により、動的なWebSocketデータをシームレスに構造化されたPDF形式に変換できるため、リアルタイムデータストリームをアーカイブ文書に変換する際の有用性が示されます。
C#でSocket.IOを利用することで、クライアントとのリアルタイムのやり取りの可能性が広がり、JavaScriptやNode.jsの領域を超えた活用が可能です。 ツールを統合することは、Socket.IOやIronPDFのようなものを.NETプロジェクトに組み込むことで、リアルタイムコミュニケーションとPDF処理の機能を大幅に強化することができます。 Socket.IOは、クライアントとサーバー間のリアルタイムで双方向のシームレスな通信を促進し、IronPDFはPDFを作成し、操作するための堅牢な機能を提供します。
IronPDF を使用して、その可能性を最大限に引き出し、C# アプリケーションで効率的かつ信頼性の高い PDF の生成と操作を保証します。