![]() |
VOOZH | about |
dotnet add package SocketIOClient --version 4.0.4
NuGet\Install-Package SocketIOClient -Version 4.0.4
<PackageReference Include="SocketIOClient" Version="4.0.4" />
<PackageVersion Include="SocketIOClient" Version="4.0.4" />Directory.Packages.props
<PackageReference Include="SocketIOClient" />Project file
paket add SocketIOClient --version 4.0.4
#r "nuget: SocketIOClient, 4.0.4"
#:package SocketIOClient@4.0.4
#addin nuget:?package=SocketIOClient&version=4.0.4Install as a Cake Addin
#tool nuget:?package=SocketIOClient&version=4.0.4Install as a Cake Tool
Languages: | English
An elegant socket.io client for .NET, it supports socket.io server v2/v3/v4, and has implemented http polling and websocket.
👁 Build Status
👁 NuGet
👁 NuGet
Connect to a Socket.IO server to receive and emit events.
var client = new SocketIO(new Uri("http://localhost:11400"));
client.On("event", ctx =>
{
// RawText: ["event","Hello World!", 1, {\"Name\":\"Alice\",\"Age\":18}]
// The first element in the array is the event name,
// and the subsequent elements are the data carried with the event.
Console.WriteLine(ctx.RawText);
// Use index 0 to access the first item in the data payload, which is of type string.
var message = ctx.GetValue<string>(0)!;
Console.WriteLine(message); // Hello World!
// Use index 1 to access the second data item in the payload. The data type is int.
var id = ctx.GetValue<int>(1);
Console.WriteLine(id); // 1
// Use index 2 to access the third data item in the payload. The data type is User.
var user = ctx.GetValue<User>(2)!;
Console.WriteLine($"Name: {user.Name}, Age: {user.Age}"); // Name: Alice, Age: 18
return Task.CompletedTask;
});
An overload is provided here to allow custom configuration of the options.
var client = new SocketIO(new Uri("http://localhost:11400"), new SocketIOOptions
{
Query = new NameValueCollection
{
["user"] = "Alice"
},
// ...
});
| Option | Default Value | Description |
|---|---|---|
| Path | /socket.io | The service endpoint path. |
| Reconnection | true | If the initial connection attempt fails, set this to true to keep retrying until the maximum number of reconnection attempts is reached. Set it to false to fail immediately without any further retry attempts. |
| ReconnectionAttempts | 10 | When Reconnection is set to true, the client will automatically retry if the connection fails. The number of retry attempts is determined by ReconnectionAttempts. |
| ReconnectionDelayMax | 5000 | After a reconnection attempt fails, the client will wait for a random delay before trying again. ReconnectionDelayMax defines the upper bound of that random delay. |
| ConnectionTimeout | 30s | The timeout duration for each connection attempt. |
| Query | null | Before the connection is established, the client can use this parameter to send query string values to the server. |
| EIO | V4 | For Socket.IO server v2.x, please set EIO = 3. |
| ExtraHeaders | null | Send the request headers with each request to the server. These values can be used during the handshake phase. |
| Transport | Polling | By default, HTTP polling is used. When AutoUpgrade is set to true, the connection will automatically upgrade to WebSocket when possible. If the server only supports WebSocket, set Transport = TransportProtocol.WebSocket. |
| AutoUpgrade | true | After the handshake, if the server supports WebSocket while the client is currently using polling, the connection will be upgraded to WebSocket. |
| Auth | null | Configure connection credentials. This feature is not supported when EIO = 3. |
Emit an event with a callback function. After the server finishes processing, it will invoke the client’s callback function and pass back the relevant data.
Client
await client.EmitAsync("hi", ["Hi, I'm Client"], ack =>
{
Console.WriteLine(ack.RawText);
// RawText: ["Hi, I'm Client","Hi, I'm Server"]
var message1 = ack.GetValue<string>(0)!;
Console.WriteLine(message1); // Hi, I'm Client
var message2 = ack.GetValue<string>(1)!;
Console.WriteLine(message2); // Hi, I'm Server
return Task.CompletedTask;
});
Server
socket.on('hi', (m1, fn) => {
fn(m1, 'Hi, I\'m Server');
});
Listen for an event that includes a callback function. After the client finishes processing, it will send the relevant data back to the server. Once the server receives the data, it will execute its callback function.
Client
client.On("add", async ctx =>
{
var a = ctx.GetValue<int>(0);
var b = ctx.GetValue<int>(1);
var c = a + b;
await ctx.SendAckDataAsync([c]);
});
Server
socket.emit('add', 1, 2, c => {
console.log(c); // 3
});
Send and receive complex data types that include byte[]. By default, System.Text.Json is used for JSON serialization.
class FileDTO
{
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("mimeType")]
public string MimeType { get; set; }
[JsonPropertyName("bytes")]
public byte[] Bytes { get; set; }
}
The above example uses [JsonPropertyName] to customize JSON property names. Global configuration via JsonSerializerOptions is also supported.
await client.EmitAsync("1:emit", [
new FileDTO
{
Name = "template.html",
MimeType = "text/html",
Bytes = Encoding.UTF8.GetBytes("<div>test</div>")
}
]);
client.On("new files", ctx =>
{
// RawText: ["new files", {"name":"template.html","mimeType":"text/html","bytes":{"_placeholder":true,"num":0}}]
var result = ctx.GetValue<FileDTO>();
Console.WriteLine(Encoding.UTF8.GetString(result.Bytes))
});
By default, System.Text.Json is used for serialization and deserialization. If you want to configure JsonSerializerOptions:
var client = new SocketIO(new Uri("http://localhost:11400"), services =>
{
services.AddSystemTextJson(new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
});
Of course, if you prefer to use Newtonsoft.Json, you need to install SocketIOClient.Serializer.NewtonsoftJson.
var client = new SocketIO(new Uri("http://localhost:11400"), services =>
{
services.AddNewtonsoftJson(new JsonSerializerSettings());
});
If your socket.io server uses a certificate issued by a trusted CA, you should not use these APIs to avoid potential security risks.
However, if your socket.io server uses a self-signed certificate, you may need to customize the certificate validation logic:
var client = new SocketIO(new Uri("http://localhost:11400"), services =>
{
services.AddSingleton<HttpClient>(_ =>
{
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (s, cert, chain, policyError) =>
{
var isValid = ...
return isValid;
}
};
return new HttpClient(handler);
});
});
var client = new SocketIO(new Uri("http://localhost:11400"), services =>
{
services.AddSingleton(new WebSocketOptions
{
RemoteCertificateValidationCallback = (s, cert, chain, policyError) =>
{
var isValid = ...
return isValid;
};
});
});
Notes:
- By default, the client communicates with the server using polling first. If the server supports WebSocket, the connection will be upgraded to a WebSocket channel. In this scenario, you may need to configure CertificateValidationCallback for both transports.
WebSocketOptionsalso exists inSystem.Net.WebSockets(.NET), which does not have aRemoteCertificateValidationCallbackproperty and will cause a compile error. Make sure you're usingSocketIOClient.Protocol.WebSocket.WebSocketOptions, either via an explicitusing SocketIOClient.Protocol.WebSocket;or by using the fully qualified name.
In some network environments, a proxy must be configured in order to communicate with the server. Proxy can also be used for development and debugging purposes to capture and inspect the entire interaction.
var client = new SocketIO(new Uri("http://localhost:11400"), services =>
{
services.AddSingleton<HttpClient>(_ =>
{
var handler = new HttpClientHandler
{
Proxy = new WebProxy(proxyUrl),
UseProxy = true
};
return new HttpClient(handler);
});
});
var client = new SocketIO(new Uri("http://localhost:11400"), services =>
{
services.AddSingleton(new WebSocketOptions
{
Proxy = new WebProxy(proxyUrl)
});
});
Note: By default, the client communicates with the server using polling first. If the server supports WebSocket, the connection will be upgraded to a WebSocket channel. In this case, you may need to configure a proxy for both transports.
To further obtain internal logs for observing its internal behavior, you can use the following approach:
var client = new SocketIO(new Uri("http://localhost:11400"), new SocketIOOptions(), services =>
{
services.AddLogging(builder =>
{
builder.SetMinimumLevel(LogLevel.Trace);
builder.AddConsole();
});
});
Here, Microsoft.Extensions.Logging.Console is used as the logging provider. For more logging providers, please refer to: Third-party logging providers
This library currently follows the software testing pyramid model, with 95% unit test coverage. You can view the coverage details in the Code Coverage section of the Azure DevOps interface.
If you need to run the integration tests locally:
cd socket.io-client-csharp/tests/socket.io
npm run install-all # Install the dependencies. This only needs to be done once.
npm run start # Start socket.io server for integration testing
TaskCompletionSource.SetResult()TaskScheduler.UnobservedTaskExceptionAfter that, you can run the integration tests.
<img src="https://socket.io/images/logo.svg" width=100px/> <img src="https://github.com/darrachequesne.png" width=100px/>
Thank socket.io and darrachequesne for sponsoring the project on Open Collective.
We would like to thank JetBrains for supporting the project with free licenses of their fantastic tools.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 net5.0 was computed. net5.0-windows net5.0-windows was computed. net6.0 net6.0 was computed. net6.0-android net6.0-android was computed. net6.0-ios net6.0-ios was computed. net6.0-maccatalyst net6.0-maccatalyst was computed. net6.0-macos net6.0-macos was computed. net6.0-tvos net6.0-tvos was computed. net6.0-windows net6.0-windows was computed. net7.0 net7.0 was computed. net7.0-android net7.0-android was computed. net7.0-ios net7.0-ios was computed. net7.0-maccatalyst net7.0-maccatalyst was computed. net7.0-macos net7.0-macos was computed. net7.0-tvos net7.0-tvos was computed. net7.0-windows net7.0-windows was computed. net8.0 net8.0 is compatible. net8.0-android net8.0-android was computed. net8.0-browser net8.0-browser was computed. net8.0-ios net8.0-ios was computed. net8.0-maccatalyst net8.0-maccatalyst was computed. net8.0-macos net8.0-macos was computed. net8.0-tvos net8.0-tvos was computed. net8.0-windows net8.0-windows was computed. net9.0 net9.0 was computed. net9.0-android net9.0-android was computed. net9.0-browser net9.0-browser was computed. net9.0-ios net9.0-ios was computed. net9.0-maccatalyst net9.0-maccatalyst was computed. net9.0-macos net9.0-macos was computed. net9.0-tvos net9.0-tvos was computed. net9.0-windows net9.0-windows was computed. net10.0 net10.0 was computed. net10.0-android net10.0-android was computed. net10.0-browser net10.0-browser was computed. net10.0-ios net10.0-ios was computed. net10.0-maccatalyst net10.0-maccatalyst was computed. net10.0-macos net10.0-macos was computed. net10.0-tvos net10.0-tvos was computed. net10.0-windows net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 netcoreapp2.0 was computed. netcoreapp2.1 netcoreapp2.1 was computed. netcoreapp2.2 netcoreapp2.2 was computed. netcoreapp3.0 netcoreapp3.0 was computed. netcoreapp3.1 netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 netstandard2.0 is compatible. netstandard2.1 netstandard2.1 was computed. |
| .NET Framework | net461 net461 was computed. net462 net462 was computed. net463 net463 was computed. net47 net47 was computed. net471 net471 was computed. net472 net472 was computed. net48 net48 was computed. net481 net481 was computed. |
| MonoAndroid | monoandroid monoandroid was computed. |
| MonoMac | monomac monomac was computed. |
| MonoTouch | monotouch monotouch was computed. |
| Tizen | tizen40 tizen40 was computed. tizen60 tizen60 was computed. |
| Xamarin.iOS | xamarinios xamarinios was computed. |
| Xamarin.Mac | xamarinmac xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos xamarinwatchos was computed. |
Showing the top 5 NuGet packages that depend on SocketIOClient:
| Package | Downloads |
|---|---|
|
ElectronNET.API
Building cross platform electron based desktop apps with .NET Core and ASP.NET Core. This package contains the API to access the "native" electron API. |
|
|
SocketIOClient.Newtonsoft.Json
socket.io-client json serialization/deserialization for Newtonsoft.Json |
|
|
DigitalRuby.ExchangeSharp
ExchangeSharp is a C# API for working with various cryptocurrency exchanges. Web sockets are also supported for some exchanges. |
|
|
gomake-common-library
Package Description |
|
|
NuGetGirlCRM
Dating CRM Package |
Showing the top 7 popular GitHub repositories that depend on SocketIOClient:
| Repository | Stars |
|---|---|
|
ElectronNET/Electron.NET
:electron: Build cross platform desktop apps with ASP.NET Core (Razor Pages, MVC, Blazor).
|
|
|
ArduPilot/MissionPlanner
Mission Planner Ground Control Station for ArduPilot (c# .net)
|
|
|
visualHFT/VisualHFT
VisualHFT is a WPF/C# desktop GUI that shows market microstructure in real time. You can track advanced limit‑order‑book dynamics and execution quality, then use its modular plugins to shape the analysis to your workflow.
|
|
|
DigitalRuby/ExchangeSharp
ExchangeSharp is a powerful, fast and easy to use .NET/C# API for interfacing with many crypto currency exchanges. REST and web sockets are supported.
|
|
|
automuteus/amonguscapture
Capture of the local Among Us executable state
|
|
|
DeSinc/SallyBot
AI Chatbot coded in Discord.net C#
|
|
|
jensroth-git/WinLaunch
macOS Launchpad for Windows
|
| Version | Downloads | Last Updated |
|---|---|---|
| 4.0.4 | 14,367 | 5/22/2026 |
| 4.0.3 | 12,561 | 3/28/2026 |
| 4.0.2 | 3,265 | 3/26/2026 |
| 4.0.1 | 5,411 | 2/28/2026 |
| 4.0.0.2 | 15,720 | 2/6/2026 |
| 4.0.0.1 | 986 | 2/2/2026 |
| 4.0.0 | 476 | 1/31/2026 |
| 3.1.2 | 566,121 | 8/18/2024 |
| 3.1.1 | 251,592 | 9/5/2023 |
| 3.1.0 | 2,102 | 8/27/2023 |
| 3.0.8 | 447,865 | 3/4/2023 |
| 3.0.7 | 37,249 | 11/29/2022 |
| 3.0.7-alpha.3 | 275 | 11/29/2022 |
| 3.0.7-alpha.2 | 302 | 11/29/2022 |
| 3.0.7-alpha.1 | 368 | 11/6/2022 |
| 3.0.6 | 277,851 | 3/17/2022 |
| 3.0.5 | 56,848 | 1/12/2022 |
| 3.0.4 | 38,609 | 12/6/2021 |
| 3.0.4-alpha.1 | 427 | 11/18/2021 |
| 3.0.3 | 19,617 | 9/24/2021 |