SocketIOSharp2 2.0.5

Requires NuGet 2.12 or higher.

dotnet add package SocketIOSharp2 --version 2.0.5                
NuGet\Install-Package SocketIOSharp2 -Version 2.0.5                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="SocketIOSharp2" Version="2.0.5" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add SocketIOSharp2 --version 2.0.5                
#r "nuget: SocketIOSharp2, 2.0.5"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install SocketIOSharp2 as a Cake Addin
#addin nuget:?package=SocketIOSharp2&version=2.0.5

// Install SocketIOSharp2 as a Cake Tool
#tool nuget:?package=SocketIOSharp2&version=2.0.5                

New

This is a fork of SocketIOSharp:master with additional support for socket connection pre-processing!

using (SocketIOServer server = new SocketIOServer(newSocketIOServerOption(1009, AllowEIO3: true, VerificationTimeout: 1001)))
{
    Console.WriteLine("Listening on " + server.Option.Port);
    server.OnConnecting((obj) =>
    {
        var token = obj.Item1["token"];
        if (string.IsNullOrWhiteSpace(token))
        {
            Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} The authentication fails and the connection is denied");
        }
        server.AddVerificationResult(obj.Item2, string.IsNullOrWhiteSpace(token));
    });
    server.OnConnection((socket) =>
    {
        Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff} Client connected!");
    });

    server.Start();
}

Added

1.SocketIOSharp/Common/SocketIOEvent.cs

public static class SocketIOEvent
{
    public static readonly string CONNECTING = "connecting";
}

2.SocketIOSharp/Server/SocketIOServer.Event.cs

partial class SocketIOServer
{
    //private class SocketIOConnectionHandler : Emitter<SocketIOConnectionHandler, string, SocketIOSocket> { }
    private class SocketIOConnectionHandler : Emitter<SocketIOConnectionHandler, string, object> { }
    private readonly SocketIOConnectionHandler ConnectionHandlerManager = new SocketIOConnectionHandler();
    public SocketIOServer OnConnection(Action<SocketIOSocket> Callback)
    {
        //ConnectionHandlerManager.On(SocketIOEvent.CONNECTION, Callback);
        ConnectionHandlerManager.On(SocketIOEvent.CONNECTION, (Client) => Callback(Client as SocketIOSocket));
        return this;
    }

    public SocketIOServer OnConnecting(Action<Tuple<System.Collections.Specialized.NameValueCollection, string>> Callback)
    {
        ConnectionHandlerManager.On(SocketIOEvent.CONNECTING, (Client) => Callback(Client as Tuple<System.Collections.Specialized.NameValueCollection, string>));
        return this;
    }
}

3.SocketIOSharp/Server/SocketIOServerOption.cs

public SocketIOServerOption(ulong VerificationTimeout = 1000) : base(VerificationTimeout) { }

4.SocketIOSharp/Server/SocketIOServer.cs

public SocketIOServer(SocketIOServerOption Option)
{
    Server.OnConnecting(OnConnecting);
}
#region On Connecting Handle
private void OnConnecting(Tuple<System.Collections.Specialized.NameValueCollection, string> callBack)
{
    ConnectionHandlerManager.Emit(SocketIOEvent.CONNECTING, new Tuple<System.Collections.Specialized.NameValueCollection, string>(callBack.Item1, callBack.Item2));
}
/// <summary>
/// Add Verification Result
/// </summary>
/// <param name="conId">connection id</param>
/// <param name="abort">result</param>
public void AddVerificationResult(string conId, bool abort = false)
{
    Server.VerificationResult.TryAdd(conId, abort);
} 
#endregion

SocketIOSharp

SocketIOSharp is a Socket.IO protocol revision 4 library based on Engine.IO and WebSocket protocol. It depends on EngineIOSharp to use Engine.IO protocol.

Installation

  • Nuget gallery

  • Command Install-Package SocketIOSharp2 in nuget package manager console.

Usage

Client

Namespace

using EngineIOSharp.Common.Enum;
using SocketIOSharp.Client;
using SocketIOSharp.Common;

Constructor

SocketIOClient client = new SocketIOClient(new SocketIOClientOption(EngineIOScheme.http, "localhost", 9001));
SocketIOClientOption
  • Essential Parameters

    • Scheme : Scheme to connect to. It can be EngineIOScheme.http or EngineIOScheme.https. Internally, it supports ws and wss.

    • Host : Host to connect to.

    • Port : Port to connect to.

  • Optional Parameters

    • PolicyPort : Port the policy server listens on. Defaults to 843.

    • Path : Path to connect to. Defaults to "/socket.io".

    • Reconnection : Whether to reconnect to server after Socket.IO client is closed or not.

    • ReconnectionAttempts : Number of reconnection attempts before giving up.

    • ReconnectionDelay : How ms to initially wait before attempting a new reconnection.

    • ReconnectionDelayMax : Maximum amount of time to wait between reconnections. Each attempt increases the ReconnectionDelay by 2x along with a randomization.

    • RandomizationFactor : 0 ⇐ RandomizationFactor ⇐ 1.

    • Query : Parameters that will be passed for each request to the server. Defaults to null.

    • Upgrade : Whether the client should try to upgrade the transport. Defaults to true.

    • RemeberUpgrade : Whether the client should bypass normal upgrade process when previous websocket connection is succeeded. Defaults to false.

    • ForceBase64 : Forces base 64 encoding for transport. Defaults to false.

    • WithCredentials : Whether to include credentials such as cookies, authorization headers, TLS client certificates, etc. with polling requests. Defaults to false.

    • TimestampRequests : Whether to add the timestamp with each transport request. Polling requests are always stamped. Defaults to null.

    • TimestampParam : Timestamp parameter. Defaults to "t".

    • Polling : Whether to include polling transport. Defaults to true.

    • PollingTimeout : Timeout for polling requests in milliseconds. Defaults to 0, which waits indefinitely.

    • WebSocket : Whether to include websocket transport. Defaults to true.

    • WebSocketSubprotocols : List of websocket subprotocols. Defaults to null.

    • ExtraHeaders : Headers that will be passed for each request to the server. Defaults to null.

    • ClientCertificates : The collection of security certificates that are associated with each request. Defaults to null.

    • ClientCertificateSelectionCallback : Callback used to select the certificate to supply to the server. Defaults to null.

    • ServerCertificateValidationCallback : Callback method to validate the server certificate. Defaults to null and server certificate will be always validated.

Connect

client.Connect();

Disconnect

client.Close();

or

client.Dispose();

Since SocketIOClient implements IDisposable interface, it will be automatically disconnect when SocketIOClient.Dispose is called.

Handlers

For convenient usage, it is implemented to can be used as Javascript style.

Event handlers
client.On(SocketIOClient.Event.CONNECTION, () =>
{
  Console.WriteLine("Connected!");
});

client.On(SocketIOClient.Event.DISCONNECT, () =>
{
  Console.WriteLine("Disconnected!");
});

client.On(SocketIOClient.Event.ERROR, (JToken[] Data) => // Type of argument is JToken[].
{
  if (Data != null && Data.Length > 0 && Data[0] != null)
  {
    Console.WriteLine("Error : " + Data[0]);
  }
  else
  {
    Console.WrtieLine("Unkown Error");
  }
});

client.On("message", (Data) => // Argument can be used without type.
{
  if (Data != null && Data.Length > 0 && Data[0] != null)
  {
    Console.WriteLine("Message : " + Data[0]);
  }
});

client.On("CustomEvent", CustomEventHandler); // Handler can be method.
client.On(9001, ItsOverNineThousands); // Type of event is JToken. So, it can be a number.

client.Off(9001, ItsOverNineThousands); // Remove 9001 event handler.
ACK handlers
client.On("ACK1", (SocketIOAckEvent EventArgument) =>
{
  // Type of SocketIOAckEvent.Data is JToken[].
  // Type of SocketIOAckEvent.Callback is Action<JToken[]>.
  
  Console.Write("On event ack1 : " + EventArgument.Data);
});

client.On("ACK2", (EventArgument) => // Argument can be used without type.
{
  Console.Write("On event ack2 : " + EventArgument.Data);
});

client.On("ACK3", CustomAckHandler); // Handler can be method.
client.On(42, LifeTheUniverseAndTheEverything); // Type of event is JToken. So, it can be a number.

client.Off(42, LifeTheUniverseAndTheEverything); // Remove 42 ack handler.
SocketIOClient.Event
public static class Event
{
  public static readonly string CONNECTION = "connection";
  public static readonly string DISCONNECT = "disconnect";
  public static readonly string ERROR = "error";
}

These are the common basic Socket.IO events.

Emit

client.Emit("Event without data and ack");

client.Emit("Event only with data", "Hello world");

client.Emit("Event only with ack, action as lambda", (Data) => Console.WriteLine("ACK : " + Data));
client.Emit("Event only with ack, action as method", Console.WriteLine);

client.Emit("Event with data and ack, action as lambda", 9001, (Data) => Console.WriteLine("ACK : " + Data));
client.Emit("Event with data and ack, action as method", 42, Console.WriteLine);
// Type of data is JToken. So, it can be a number.

Server

Namespace

using SocketIOSharp.Server;

Constructor

SocketIOServer server = new SocketIOServer(new SocketIOServerOption(9001));
SocketIOServerOption
  • Essential Parameters

    • Port : Port to listen.
  • Optional Parameters

    • Path : Path to listen. Defaults to "/socket.io".

    • Secure : Whether to secure connections. Defatuls to false.

    • PingTimeout : How many ms without a pong packet to consider the connection closed. Defatuls to 5000.

    • PingInterval : How many ms before sending a new ping packet. Defatuls to 25000.

    • UpgradeTimeout : How many ms before an uncompleted transport upgrade is cancelled. Defatuls to 10000.

    • Polling : Whether to accept polling transport. Defatuls to true.

    • WebSocket : Whether to accept websocket transport. Defatuls to true.

    • AllowUpgrade : Whether to allow transport upgrade. Defatuls to true.

    • SetCookie : Whether to use cookie. Defatuls to true.

    • SIDCookieName : Name of sid cookie. Defatuls to "io".

    • Cookies : Configuration of the cookie that contains the client sid to send as part of handshake response headers. This cookie might be used for sticky-session. Defatuls to null.

    • AllowHttpRequest : A function that receives a given handshake or upgrade http request as its first parameter, and can decide whether to continue or not. Defatuls to null.

    • AllowWebSocket : A function that receives a given handshake or upgrade websocket connection as its first parameter, and can decide whether to continue or not. Defatuls to null.

    • InitialData : An optional packet which will be concatenated to the handshake packet emitted by Engine.IO. Defatuls to null.

    • ServerCertificate : The certificate used to authenticate the server. Defatuls to null.

    • ClientCertificateValidationCallback : Callback used to validate the certificate supplied by the client. Defatuls to null and client certificate will be always validated.

Start

server.Start();

Stop

server.Stop();

or

server.Dispose();

Since SocketIOServer implements IDisposable interface, it will be automatically stoped when SocketIOServer.Dispose is called.

Connection

For convenient usage, it is implemented to can be used as Javascript style.

server.OnConnection((SocketIOSocket socket) =>
{
  Console.WriteLine("Client connected!");

  socket.On("input", (Data) =>
  {
    foreach (JToken Token in Data)
    {
      Console.Write(Token + " ");
    }

    Console.WriteLine();
    socket.Emit("echo", Data);
  });

  socket.On(SocketIOEvent.DISCONNECT, () =>
  {
    Console.WriteLine("Client disconnected!");
  });
});
SocketIOSocket
  • SocketIOSocket is a type of parameter in SocketIOServer.OnConnection event callback. It can be used similarly as SocketIOClient.
Disconnect
socket.Close();

or

socket.Dispose();

Since SocketIOSocket implements IDisposable interface, it will be automatically disconnected when SocketIOSocket.Dispose is called.

Handlers

For convenient usage, it is implemented to can be used as Javascript style.

Event handlers
client.On(SocketIOClient.Event.DISCONNECT, () =>
{
  Console.WriteLine("Disconnected!");
});

client.On(SocketIOClient.Event.ERROR, (JToken[] Data) => // Type of argument is JToken[].
{
  if (Data != null && Data.Length > 0 && Data[0] != null)
  {
    Console.WriteLine("Error : " + Data[0]);
  }
  else
  {
    Console.WrtieLine("Unkown Error");
  }
});

client.On("message", (Data) => // Argument can be used without type.
{
  if (Data != null && Data.Length > 0 && Data[0] != null)
  {
    Console.WriteLine("Message : " + Data[0]);
  }
});

client.On("CustomEvent", CustomEventHandler); // Handler can be method.
client.On(9001, ItsOverNineThousands); // Type of event is JToken. So, it can be a number.

client.Off(9001, ItsOverNineThousands); // Remove 9001 event handler.
  • There is no SocketIOSocket.On(SocketIOEvent.CONNECTION) event since it is already opened when SocketIOServer.OnConnection event callback is called.
ACK handlers
client.On("ACK1", (SocketIOAckEvent EventArgument) =>
{
  // Type of SocketIOAckEvent.Data is JToken[].
  // Type of SocketIOAckEvent.Callback is Action<JToken[]>.
  
  Console.Write("On event ack1 : " + EventArgument.Data);
});

client.On("ACK2", (EventArgument) => // Argument can be used without type.
{
  Console.Write("On event ack2 : " + EventArgument.Data);
});

client.On("ACK3", CustomAckHandler); // Handler can be method.
client.On(42, LifeTheUniverseAndTheEverything); // Type of event is JToken. So, it can be a number.

client.Off(42, LifeTheUniverseAndTheEverything); // Remove 42 ack handler.
Emit
client.Emit("Event without data and ack");

client.Emit("Event only with data", "Hello world");

client.Emit("Event only with ack, action as lambda", (Data) => Console.WriteLine("ACK : " + Data));
client.Emit("Event only with ack, action as method", Console.WriteLine);

client.Emit("Event with data and ack, action as lambda", 9001, (Data) => Console.WriteLine("ACK : " + Data));
client.Emit("Event with data and ack, action as method", 42, Console.WriteLine);
// Type of data is JToken. So, it can be a number.

Emit

server.Emit("Event without data and ack");

server.Emit("Event only with data", "Hello world");

server.Emit("Event only with ack, action as lambda", (Data) => Console.WriteLine("ACK : " + Data));
server.Emit("Event only with ack, action as method", Console.WriteLine);

server.Emit("Event with data and ack, action as lambda", 9001, (Data) => Console.WriteLine("ACK : " + Data));
server.Emit("Event with data and ack, action as method", 42, Console.WriteLine);
// Type of data is JToken. So, it can be a number.

Maintenance

Welcome to report issue or create pull request. I will check it happily.

Dependencies

License

SocketIOSharp is under The MIT License.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 is compatible. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net40 is compatible.  net403 was computed.  net45 is compatible.  net451 was computed.  net452 was computed.  net46 was computed.  net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.0.5 493 8/17/2023
2.0.4 1,087 6/15/2023

add socket connection pre-processing(by SocketIOSharp/2.0.3)