GithubHelp home page GithubHelp logo

sacoo7 / socketclusterclientdotnet Goto Github PK

View Code? Open in Web Editor NEW
69.0 7.0 16.0 6.27 MB

C# client for socketcluster framework in node.js

Home Page: http://socketcluster.io/#!/

License: Apache License 2.0

C# 100.00%
socketcluster xamarin pub-sub c-sharp client silverlight windows-phone mono

socketclusterclientdotnet's Introduction

.Net Socketcluster Client

Overview

This client provides following functionality

  • Support for emitting and listening to remote events
  • Automatic reconnection
  • Pub/sub
  • Authentication (JWT)

Client supports following platforms

  • .Net 2.0
  • .Net 3.5
  • .Net 4.0
  • .Net standard 1.3 onwards
  • .Net Core 1.0 onwards
  • Xamarin.Android
  • Xamarin.iOS
  • Unity

License

Apache License, Version 2.0

Usage via Nuget

    Install-Package ScClient.Official

Nuget Gallery link : https://www.nuget.org/packages/ScClient.Official/

Usage using source files

Library is built on top of Websocket4Net and Newtonsoft.Json. Install those packages via nuget and add source files into project

Description

Create instance of Socket class by passing url of socketcluster-server end-point

    //Create a socket instance
    string url = "ws://localhost:8000/socketcluster/";
    var socket = new Socket(url);

Important Note : Default url to socketcluster end-point is always ws://somedomainname.com/socketcluster/.

Registering basic listeners

Create a class implementing BasicListener interface and pass it's instance to socket setListener method

        internal class MyListener : IBasicListener
        {
            public void OnConnected(Socket socket)
            {
                Console.WriteLine("connected got called");
            }

            public void OnDisconnected(Socket socket)
            {
                Console.WriteLine("disconnected got called");
            }

            public void OnConnectError(Socket socket, ErrorEventArgs e)
            {
                Console.WriteLine("on connect error got called");
            }

            public void OnAuthentication(Socket socket, bool status)
            {
                Console.WriteLine(status ? "Socket is authenticated" : "Socket is not authenticated");
            }

            public void OnSetAuthToken(string token, Socket socket)
            {
                socket.setAuthToken(token);
                Console.WriteLine("on set auth token got called");
            }

        }

        internal class Program
        {
            public static void Main(string[] args)
            {
                var socket = new Socket("ws://localhost:8000/socketcluster/");
                socket.SetListerner(new MyListener());
            }
        }

Connecting to server

  • For connecting to server:
    //This will send websocket handshake request to socketcluster-server
    socket.Connect();
  • By default reconnection to server is not enabled , to enable it :
    //This will set automatic-reconnection to server with delay of 3 seconds and repeating it for 30 times
    socket.SetReconnectStrategy(new ReconnectStrategy().SetMaxAttempts(30));
    socket.Connect()
  • To disable reconnection :
   socket.SetReconnectStrategy(null);

Emitting and listening to events

Event emitter

  • eventname is name of event and message can be String, boolean, Long or JSON-object
    socket.Emit(eventname,message);

    //socket.Emit("chat","Hi");
  • To send event with acknowledgement
    socket.Emit("chat", "Hi", (eventName, error, data) =>
    {
       //If error and data is String
       Console.WriteLine("Got message for :"+eventName+" error is :"+error+" data is :"+data);
    });

Event Listener

  • For listening to events :

The object received can be String, Boolean, Long or JSONObject.

    socket.On("chat", (eventName, data) =>
    {
        Console.WriteLine("got message "+ data+ " from event "+eventName);
    });
  • To send acknowledgement back to server
    socket.On("chat", (eventName, data, ack) =>
    {
        Console.WriteLine("got message "+ data+ " from event "+eventName);
        ack(name, "No error", "Hi there buddy");
    });

Implementing Pub-Sub via channels

Creating channel

  • For creating and subscribing to channels:
    var channel=socket.CreateChannel(channelName);
   //var channel=socket.CreateChannel("yolo");


    /**
     * without acknowledgement
     */
     channel.Subscribe();

    /**
     * with acknowledgement
     */

    channel.Subscribe((channelName, error, data) =>
    {
       if (error == null)
       {
             Console.WriteLine("Subscribed to channel "+channelName+" successfully");
       }
    });
  • For getting list of created channels :
    List<Socket.Channel> channels = socket.GetChannels();
  • To get channel by name :
    var channel=socket.GetChannelByName("yell");
    //Returns null if channel of given name is not present

Publishing event on channel

  • For publishing event :
       // message can have any data type
    /**
     * without acknowledgement
     */
     channel.Publish(message);

    /**
     * with acknowledgement
     */
       channel.Publish(message, (channelName, error, data) =>
       {
            if (error == null) {
               Console.WriteLine("Published message to channel "+channelName+" successfully");
            }
       });

Listening to channel

  • For listening to channel event :
    //If instance of channel exists
    channel.OnMessage((channelName, data) =>
    {
         Console.WriteLine("Got message for channel "+channelName+" data is "+data);
    });

    //or
    socket.OnSubscribe(channelName, (channelName, data) =>
    {
        Console.WriteLine("Got message for channel "+channelName+" data is "+data);
    });

Un-subscribing to channel

    /**
     * without acknowledgement
     */

     channel.Unsubscribe();

    /**
     * with acknowledgement
     */

    channel.Unsubscribe((name, error, data) =>
    {
        if (error == null) {
            Console.WriteLine("channel unsubscribed successfully");
        }
    });

Handling SSL connection with server

To enable or disable SSL certficate verification use

socket.SetSSLCertVerification(true/false);

Setting HTTP proxy with server

//args, string : host , int : port
socket.SetProxy(host,port);

Star the repo. if you love the client :).

socketclusterclientdotnet's People

Contributors

bgapinski avatar janusw avatar sachinsh76 avatar sacoo7 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

socketclusterclientdotnet's Issues

There's no way to re-auth

Token authentication works fine until the token expires but then there is no way to re-authenticate with a new or refreshed token. The only way I can see is to reconnect which isn't ideal.

[Request] A C# client for unity game engine.

When I import this lib into Unity game engine, there are errors.

Assets/socketcluster/ScClient/Proxy/HttpConnectProxy.cs(75,35): error CS1061: Type System.Net.EndPoint' does not contain a definition for ConnectAsync' and no extension method ConnectAsync' of type System.Net.EndPoint' could be found. Are you missing an assembly reference?

Assets/socketcluster/ScClient/Proxy/HttpConnectProxy.cs(145,39): error CS1061: Type byte[]' does not contain a definition for SearchMark' and no extension method SearchMark' of type byte[]' could be found. Are you missing an assembly reference?

Assets/socketcluster/ScClient/Socket.cs(74,29): error CS0121: The call is ambiguous between the following methods or properties: System.Linq.LINQ.FirstOrDefault<ScClient.Socket.Channel>(this System.Collections.Generic.IEnumerable<ScClient.Socket.Channel>, System.Predicate<ScClient.Socket.Channel>)' and System.Linq.Enumerable.FirstOrDefault<ScClient.Socket.Channel>(this System.Collections.Generic.IEnumerable<ScClient.Socket.Channel>, System.Func<ScClient.Socket.Channel,bool>)'

Can anyone help me? Thank you.

Reconnects automatically after successfully emitting disconnect

The problem I face is that after calling disconnect the client automatically connects to the server. Which causes "hung up" warning when closing the winform.

I'm testing the code with default server.js code downloaded from npm.
The winform code:

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    Me.DisconnectFromServer()
End Sub

 Sub DisconnectFromServer()
    For Each scc As Socket In SCClientList
        scc.Disconnect()
    Next
End Sub

When this code is run, immediately after disconnection the socket reconnects causing 'Socket hung up' warning on the server after the form is closed.

I understand that I can dispose the client after disconnection.

This is only a test case, but in actual usage scenario I may disconnect from the server without closing the form. Suggest a solution or work around.

Connect to server with authkey

I can use authkey to connect to server with js client like this:


function connectSocket(authKey) {
    var authEngine = new AuthEngine();
    authEngine.saveToken(TOKENKEY_STORE, authKey);

    var socket = socketCluster.connect({
        port: 8000,
        hostname: 'localhost',
        authEngine: authEngine,
        autoReconnect: false,
        multiplex: false
    });
    ...

How can I do it with C# lib?

connect error when build to ios/android using unity game engine.

I write a small code to test connectivity. It works well in unity editor.
But when I build project to ios/android, there are some errors. Could anyone help me?

// Use this for initialization
	void Start ()
	{

		//Create a socket instance
		string url = "ws://localhost:8000/socketcluster/";
		var socket = new Socket (url);
		socket.setReconnectStrategy (null);
		socket.setListerner (new SocketEventListener ());
		socket.setAuthToken ("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0eXBlIjoiYmFzZSIsImF1dGhpZCI6IjU4OWRhMWM2YTY0Zjg0MGVkYTJlZDkwNCIsInVzZXJpZCI6IjU4OWRhMWM2YTY0Zjg0MGVkYTJlZDkwMyIsImlhdCI6MTQ4NzE1OTU5OCwiZXhwIjoxNDg3MjQ1OTk4fQ.GOHzJxF-zTfdfUvkU32EovrSimfjW5KxY7NA9YwKA4A");

		socket.on (SERVICE_PACKAGE, (eventName, package) => {
			Debug.Log ("got message " + package + " from event " + eventName);
			Debug.Log ("typeof data " + package.GetType ());

			if (package is JArray) {
				Debug.Log ("package is JArray");

				JArray datas = (JArray)package;
				Debug.Log (datas.Count);
				Debug.Log (datas [0] ["evt"]);
			}
			if (package is JObject) {
				Debug.Log ("package is JObject");

				JObject data = (JObject)package;
				Debug.Log (data ["evt"]);
			}

		});
		Debug.Log ("start connecting");
		socket.connect ();
	}

ios log:

start connecting
UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object)
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:LogFormat(LogType, Object, String, Object[])
UnityEngine.Logger:Log(LogType, Object)
Newtonsoft.Json.Utilities.CollectionWrapper`1:System.Collections.IList.get_IsFixedSize()
UnityEngine.Debug:Log(Object)
SCClient:Start()
 
(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)

NotSupportedException: /Users/builduser/buildslave/unity/build/Tools/il2cpp/il2cpp/libil2cpp/icalls/mscorlib/System.Reflection.Emit/DynamicMethod.cpp(25) : Unsupported internal call for IL2CPP:DynamicMethod::destroy_dynamic_method - System.Reflection.Emit is not supported.
  at System.Reflection.Emit.DynamicMethod.destroy_dynamic_method (System.Reflection.Emit.DynamicMethod m) [0x00000] in <filename unknown>:0 
  at System.Reflection.Emit.DynamicMethod.Finalize () [0x00000] in <filename unknown>:0 
UnityEngine.DebugLogHandler:Internal_LogException(Exception, Object)
UnityEngine.DebugLogHandler:LogException(Exception, Object)
UnityEngine.Debug:LogWarning(Object)
UnityEngine.Logger:LogException(Exception, Object)
UnityEngine.Debug:LogWarning(Object)
UnityEngine.Debug:LogException(Exception)
UnityEngine.UnhandledExceptionHandler:PrintException(String, Exception)
UnityEngine.UnhandledExceptionHandler:HandleUnhandledException(Object, UnhandledExceptionEventArgs)
System.UnhandledExceptionEventHandler:Invoke(Object, UnhandledExceptionEventArgs)
 
(Filename: currently not available on il2cpp Line: -1)

NotSupportedException: /Users/builduser/buildslave/unity/build/Tools/il2cpp/il2cpp/libil2cpp/icalls/mscorlib/System.Reflection.Emit/DynamicMethod.cpp(20) : Unsupported internal call for IL2CPP:DynamicMethod::create_dynamic_method - System.Reflection.Emit is not supported.
  at System.Reflection.Emit.DynamicMethod.create_dynamic_method (System.Reflection.Emit.DynamicMethod m) [0x00000] in <filename unknown>:0 
  at System.Reflection.Emit.DynamicMethod.CreateDynMethod () [0x00000] in <filename unknown>:0 
  at System.Reflection.Emit.DynamicMethod.CreateDelegate (System.Type delegateType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Utilities.DynamicReflectionDelegateFactory.CreateDefaultConstructor[T] (System.Type type) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.DefaultContractResolver.GetDefaultCreator (System.Type createdType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.DefaultContractResolver.InitializeContract (Newtonsoft.Json.Serialization.JsonContract contract) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateDictionaryContract (System.Type objectType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.DefaultContractResolver.CanConvertToString (System.Type type) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract (System.Type objectType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.DefaultContractResolver.GetSerializableMembers (System.Type objectType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract (System.Type type) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, Boolean checkAdditionalContent) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.GetContractSafe (System.Object value) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.JsonSerializer.SerializeInternal (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.JsonSerializer.SerializeInternal (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.JsonSerializer.Serialize (Newtonsoft.Json.JsonWriter jsonWriter, System.Object value, System.Type objectType) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.JsonConvert.SerializeObjectInternal (System.Object value, System.Type type, Newtonsoft.Json.JsonSerializer jsonSerializer) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value, System.Type type, Formatting formatting, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value, Formatting formatting, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <filename unknown>:0 
  at Newtonsoft.Json.JsonConvert.SerializeObject (System.Object value, Formatting formatting) [0x00000] in <filename unknown>:0 
  at ScClient.Socket.OnSocketOpened (System.Object sender, System.EventArgs e) [0x00000] in <filename unknown>:0 
  at System.EventHandler.Invoke (System.Object sender, System.EventArgs e) [0x00000] in <filename unknown>:0 
  at WebSocket4Net.WebSocket.OnHandshaked () [0x00000] in <filename unknown>:0 
  at System.Collections.ObjectModel.Collection`1[T].ClearItems () [0x00000] in <filename unknown>:0 
  at WebSocket4Net.Command.Handshake.ExecuteCommand (WebSocket4Net.WebSocket session, WebSocket4Net.WebSocketCommandInfo commandInfo) [0x00000] in <filename unknown>:0 
  at WebSocket4Net.WebSocket.add_Closed (System.EventHandler value) [0x00000] in <filename unknown>:0 
  at WebSocket4Net.WebSocket.ExecuteCommand (WebSocket4Net.WebSocketCommandInfo commandInfo) [0x00000] in <filename unknown>:0 
  at WebSocket4Net.WebSocket.OnDataReceived (System.Byte[] data, Int32 offset, Int32 length) [0x00000] in <filename unknown>:0 
  at WebSocket4Net.WebSocket.client_DataReceived (System.Object sender, SuperSocket.ClientEngine.DataEventArgs e) [0x00000] in <filename unknown>:0 
  at System.EventHandler`1[TEventArgs].Invoke (System.Object sender, .TEventArgs e) [0x00000] in <filename unknown>:0 
  at SuperSocket.ClientEngine.ClientSession.OnDataReceived (System.Byte[] data, Int32 offset, Int32 length) [0x00000] in <filename unknown>:0 
  at Mono.Security.Cryptography.MD4..ctor () [0x00000] in <filename unknown>:0 
  at SuperSocket.ClientEngine.AsyncTcpSession.ProcessReceive (System.Net.Sockets.SocketAsyncEventArgs e) [0x00000] in <filename unknown>:0 
  at SuperSocket.ClientEngine.AsyncTcpSession.SocketEventArgsCompleted (System.Object sender, System.Net.Sockets.SocketAsyncEventArgs e) [0x00000] in <filename unknown>:0 
  at System.EventHandler`1[TEventArgs].Invoke (System.Object sender, .TEventArgs e) [0x00000] in <filename unknown>:0 
  at System.Net.Sockets.SocketAsyncEventArgs.OnCompleted (System.Net.Sockets.SocketAsyncEventArgs e) [0x00000] in <filename unknown>:0 
  at Sample.Proxy.ProxyConnectorBase.StartSend (System.Net.Sockets.Socket socket, System.Net.Sockets.SocketAsyncEventArgs e) [0x00000] in <filename unknown>:0 
  at System.Net.Sockets.SocketAsyncEventArgs.ReceiveCallback () [0x00000] in <filename unknown>:0 
  at System.Threading.ThreadStart.Invoke () [0x00000] in <filename unknown>:0 
UnityEngine.DebugLogHandler:Internal_LogException(Exception, Object)
UnityEngine.DebugLogHandler:LogException(Exception, Object)
UnityEngine.Debug:LogWarning(Object)
UnityEngine.Logger:LogException(Exception, Object)
UnityEngine.Debug:LogWarning(Object)
UnityEngine.Debug:LogException(Exception)
UnityEngine.UnhandledExceptionHandler:PrintException(String, Exception)
UnityEngine.UnhandledExceptionHandler:HandleUnhandledException(Object, UnhandledExceptionEventArgs)
System.UnhandledExceptionEventHandler:Invoke(Object, UnhandledExceptionEventArgs)

My socketcluster server got a warning when ios app runs.

1487214567638 - Origin: Worker (PID 56065)
   [Warning] SocketProtocolError: Did not receive #handshake from client before timeout
    at Emitter.SCSocket._onSCClose (/Users/annguyen/Documents/workspace/node/sc1/server/node_modules/socketcluster/node_modules/socketcluster-server/sc
socket.js:206:17)
    at Emitter.SCSocket.disconnect (/Users/annguyen/Documents/workspace/node/sc1/server/node_modules/socketcluster/node_modules/socketcluster-server/sc
socket.js:226:10)
    at EventEmitter.SCServer._handleHandshakeTimeout (/Users/annguyen/Documents/workspace/node/sc1/server/node_modules/socketcluster/node_modules/socke
tcluster-server/scserver.js:184:12)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)

Android app log:

02-16 10:13:06.923: I/Unity(22341): start connecting
02-16 10:13:06.923: I/Unity(22341):  
02-16 10:13:06.923: I/Unity(22341): (Filename: ./artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)
02-16 10:13:07.033: I/Unity(22341): on connect error got called
02-16 10:13:07.033: I/Unity(22341):  
02-16 10:13:07.033: I/Unity(22341): (Filename: ./artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)
02-16 10:13:07.033: I/Unity(22341): SuperSocket.ClientEngine.ErrorEventArgs
02-16 10:13:07.033: I/Unity(22341):  
02-16 10:13:07.033: I/Unity(22341): (Filename: ./artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)
02-16 10:13:07.033: I/Unity(22341): disconnected got called
02-16 10:13:07.033: I/Unity(22341):  
02-16 10:13:07.033: I/Unity(22341): (Filename: ./artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)

There is no log on my socket cluster server when my android app runs.

System.Exception: unknown server protocol version

On Xamarian.Forms, I received the following exception.

System.Exception: unknown server protocol version

    void IBasicListener.OnConnectError(Socket socket, ErrorEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Connection Error : " + e.Exception.ToString());
    }

    protected override void OnStart()
    {
        conn = new Socket("ws://73.159.237.174:8000");
        conn.SetListerner(new App());
        conn.SetReconnectStrategy(new ReconnectStrategy().SetMaxAttempts(10));
        conn.Connect();
    }

The issue appears to be WebSocket related, which leads me to believe it may have something to do with an exception within SocketClusterClient itself, rather than my specific application. Thanks,

Drew.

UPDATE:
kerryjiang/WebSocket4Net#8
This issue seems related, so I believe you have to pass the origin into WebSocket4Net. If someone could take on this task, and bring this project back to its original potential, we would all greatly appreciate that. Thanks!

Unable to install in NuGet Package

I am working in Xamarin Forms ( PCL )

Unable to install package through this link : https://www.nuget.org/packages/ScClient/1.0.0

Showing me the following error while installing :

Severity Code Description Project File Line Suppression State
Error Could not install package 'WebSocket4Net 0.14.1'. You are trying to install this package into a project that targets '.NETPortable,Version=v4.5,Profile=Profile259', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author. 0

Visiual Studio 2015 community
.Net version : 4.5
Xamarin version : 4.3.0.784

Any help regarding this issue is appreciated. Thanks in adv.

Can't connect to socket cluster server

I have a weird issue. When connecting to a a web socket server using the domain name in a xamarin mobile application, the server is logging "SocketProtocolError: Socket hung up" and from the client "System.InvalidOperationException: Operation already in progress"

When i try the code from a console application, the client connects fine and is able to send and receive data

ScClient.Offical version is 1.1.2

Socket Cluster server versions:
"dependencies": {
"connect": "3.0.1",
"express": "4.14.0",
"minimist": "1.1.0",
"morgan": "1.7.0",
"sc-errors": "^1.4.0",
"sc-framework-health-check": "^2.0.0",
"sc-hot-reboot": "^1.0.0",
"scc-broker-client": "^3.0.0",
"serve-static": "1.11.2",
"socketcluster": "^11.2.0",
"socketcluster-client": "^11.0.1"
}

public class SCService
    {
        private Socket socket;
        public SCService()
        {
            try
            {
                socket = new Socket("ws://bbtest.eu-4.evennode.com/socketcluster/");

                socket.SetReconnectStrategy(new ReconnectStrategy().SetMaxAttempts(30));
                socket.SetSslCertVerification(false);
                //socket.SetAuthToken("12345678");

                socket.SetListerner(new SocketClusterListener());
                socket.Connect();
            }
            catch (Exception ex)
            {

            }

        }

        public Socket Socket
        {
            get => socket;
        }
    }

    public class SocketClusterListener : IBasicListener
    {
        private string TAG = "SocketCluster";
        public void OnConnected(Socket socket)
        {
            Debug.WriteLine($"{TAG} - connected got called");
        }

        public void OnDisconnected(Socket socket)
        {
            Debug.WriteLine($"{TAG} - disconnected got called");
        }

        public void OnAuthentication(Socket socket, bool status)
        {
            Debug.WriteLine(status ? $"{TAG} - Socket is authenticated" : $"{TAG} - Socket is not authenticated");
        }

        public void OnSetAuthToken(string token, Socket socket)
        {
            socket.SetAuthToken(token);
            Debug.WriteLine($"{TAG} - on set auth token got called");
        }

        public void OnConnectError(Socket socket, SuperSocket.ClientEngine.ErrorEventArgs e)
        {
            Debug.WriteLine($"{TAG} - Error on Connection... {e.Exception}");
        }
    }

Exceptions not handled during reconnect and setting Reconnect strategy equal to null causes null reference exception

I experienced an exception being thrown during the reconnect procedure. Specifically the exception said an attempt to connect was refused because an attempt to connect was already in progress. I believe some exception handling is needed on line 225 referenced above.

if (!_strategy.AreAttemptsComplete())

To work around this I tried to disable to the reconnect strategy so I could write my own. This caused a null reference exception to be thrown after OnDisconnect on my own IBasicListener implementation was called. I believe I have identified the problem on line 120 referenced above. It seems after calling OnDisconnect it calls _strategy.AreAttemptsComplete() without first checking is _strategy is not null.

I have found a workaround for the latter problem, which is to set the max attempts of the reconnect strategy to 0.

dotnet 3.5 support unity 5

I am trying to installing SocketclusterClientDotNet on 3.5 dotnet project to work with socketcluster in Unity but in nuget VisualStudio is showing it need 4.5 dotnet version or more and in the github documentation is showing it support 3.5 dotnet version (Unity 5 only supports 3.5 dotnet or less) =[

Null ref

I can't seem to figure out where at WebSocket4Net.WebSocket.Send(String message) is coming from. The referenced library only has SendAsync() not Send() so something doesn't seem right here.

System.NullReferenceException: Object reference not set to an instance of an object.
   at ScClient.Socket.OnWebsocketError(Object sender, ErrorEventArgs e)
   at WebSocket4Net.WebSocket.OnError(ErrorEventArgs e)
   at WebSocket4Net.WebSocket.OnError(Exception e)
   at WebSocket4Net.WebSocket.EnsureWebSocketOpen()
   at WebSocket4Net.WebSocket.Send(String message)
   at ScClient.Socket.Publish(String channel, Object data, Ackcall ack)
   at ScClient.Socket.Channel.Publish(Object data, Ackcall ack)

JsonReaderException when updating ScClient from version 1.1.2 to 1.2.0

I have a Xamarin cross-platform application that uses ScClient.Official. When updating from version 1.1.2 to 1.2.0 via nuget, I get exceptions on both iOS and Android:

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: #. Path '', line 0, position 0.

The stacktrace on Android is the following (note that this does not include any of my own code, but only 3rd-party library code):

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: #. Path '', line 0, position 0.
  at Newtonsoft.Json.JsonTextReader.ParseValue () [0x002b3] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.JsonTextReader.Read () [0x0004c] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.JsonReader.ReadAndMoveToContent () [0x00000] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.JsonReader.ReadForType (Newtonsoft.Json.Serialization.JsonContract contract, System.Boolean hasConverter) [0x0004a] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <2073514815234917a5e8f91b0b239405>:0
  at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <2073514815234917a5e8f91b0b239405>:0
  at ScClient.Socket.OnWebsocketMessageReceived (System.Object sender, WebSocket4Net.MessageReceivedEventArgs e) [0x00029] in <a1ade55c6c65407b9c91281005d197dd>:0
  at WebSocket4Net.WebSocket.FireMessageReceived (System.String message) [0x00016] in <4cb06ef8575846faa96238206314da14>:0
  at WebSocket4Net.Command.Text.ExecuteCommand (WebSocket4Net.WebSocket session, WebSocket4Net.WebSocketCommandInfo commandInfo) [0x00007] in <4cb06ef8575846faa96238206314da14>:0
  at WebSocket4Net.WebSocket.ExecuteCommand (WebSocket4Net.WebSocketCommandInfo commandInfo) [0x00015] in <4cb06ef8575846faa96238206314da14>:0
  at WebSocket4Net.WebSocket.OnDataReceived (System.Byte[] data, System.Int32 offset, System.Int32 length) [0x00032] in <4cb06ef8575846faa96238206314da14>:0
  at WebSocket4Net.WebSocket.client_DataReceived (System.Object sender, SuperSocket.ClientEngine.DataEventArgs e) [0x00013] in <4cb06ef8575846faa96238206314da14>:0
  at SuperSocket.ClientEngine.ClientSession.OnDataReceived (System.Byte[] data, System.Int32 offset, System.Int32 length) [0x0002f] in <dbd80dafc8794140aef5960a6254d156>:0
  at SuperSocket.ClientEngine.AuthenticatedStreamTcpSession.ReadAsync () [0x00139] in <dbd80dafc8794140aef5960a6254d156>:0
  at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__7_1 (System.Object state) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/AsyncMethodBuilder.cs:1037
  at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context (System.Object state) [0x0000d] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:1370
  at System.Threading.ExecutionContext.RunInternal (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00071] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:968
  at System.Threading.ExecutionContext.Run (System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, System.Object state, System.Boolean preserveSyncCtx) [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/threading/executioncontext.cs:910
  at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem () [0x00021] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:1341
  at System.Threading.ThreadPoolWorkQueue.Dispatch () [0x00074] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:899
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback () [0x00000] in /Users/builder/jenkins/workspace/archive-mono/2019-10/android/release/mcs/class/referencesource/mscorlib/system/threading/threadpool.cs:1261

"SocketProtocolError: Socket hung up" error on server after closing program

Thought the error could have something to do with the reverse proxy but I tried different ones so that isn't the issue.

I also need a 500ms timeout before I start subscribing after starting the connection, just tell me if I expect to much or if that is something that can be fixed too or if that's something with the server ๐Ÿ˜›

SocketCluster for Unity3D

Hi.
How can i use this in Unity3D. I just copy Newtonsoft.Json dll and WebSocket4Net dll and all c# scripts to the project . Whether this will be enough ?
Maybe you can provide some integration tips for Unity .

Thanks.

Client pong timed out

So I just setup a basic socketcluster server with this C# client and javascript client but I'm getting this time out error:

[Warning] SocketProtocolError: Client pong timed out
    at Emitter.SCSocket._onSCClose (/usr/local/Tribion/Lens/socketcluster/server/node_modules/socketcluster-server/scsocket.js:207:17)
    at Timeout.<anonymous> (/usr/local/Tribion/Lens/socketcluster/server/node_modules/socketcluster-server/scsocket.js:172:10)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)
1490090617481 - Origin: Worker (PID 24541)
   [Warning] SocketProtocolError: Client pong timed out
    at Emitter.SCSocket._onSCClose (/usr/local/Tribion/Lens/socketcluster/server/node_modules/socketcluster-server/scsocket.js:207:17)
    at Timeout.<anonymous> (/usr/local/Tribion/Lens/socketcluster/server/node_modules/socketcluster-server/scsocket.js:172:10)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)
1490090625381 - Origin: Worker (PID 24541)
   [Warning] SocketProtocolError: Client pong timed out
    at Emitter.SCSocket._onSCClose (/usr/local/Tribion/Lens/socketcluster/server/node_modules/socketcluster-server/scsocket.js:207:17)
    at Timeout.<anonymous> (/usr/local/Tribion/Lens/socketcluster/server/node_modules/socketcluster-server/scsocket.js:172:10)
    at ontimeout (timers.js:365:14)
    at tryOnTimeout (timers.js:237:5)
    at Timer.listOnTimeout (timers.js:207:5)

Don't know what to do with this :|

People had this with other outdated clients, is that the problem?

Anyway thanks for your great work! Other than this it's working fine :D

Publish ScClient as class library

Hi,
Could you change the ScClient file included in the nuget package from .exe to .dll?
I created a WebJob application that references ScClient but the hosting environment (Azure) executes ScClient.exe instead of my application.
Thanks

A call to SSPI failed

Hi,

I was using visual studio 2017 on Windows 7 with target framework 4.5. But the connection failed to this issue. It also says "The message received was unexpected or badly formatted".

Any help is appreciated. Thank you!

Emit is not being received SocketCluster v16

on C# client..
SocketMessage sockeMessage = new SocketMessage();
sockeMessage.MessageType = "PatientTestResult";
sockeMessage.PatientId = (long)testResult.PatientId;
sockeMessage.DoctorId = doctor.Id;
socket.Emit("inbound", sockeMessage);

on sever side

(async () => {
for await (let {socket} of agServer.listener('connection')) {
console.log(connection: ${socket} );
(async () => {
for await (
let data of socket.receiver('inbound')
) {
console.log(inbound channel: ${data} );
(async () => {
try {
await socket.exchange.invokePublish('outbound', data);
} catch (error) {
// ... Handle potential error if broker does not acknowledge before timeout.
console.log(error: ${error});
}
})();
}
})();
}
}) ();

I never seem to receive 'inbound' on sever

Code error in HttpConnectProxy.cs: ConnectAsync

My project is for Xamarin.Forms.Android

After adding this with nuget failed, I copied the *.cs files into my project (excluding your Program.cs). Also, I deleted all of the #if/#else directives for SILVERLIGHT and WINDOWS PHONE, electing only the code I needed for my own Android device. (Using these directives won't work in Xamarin net standard 2 (Portable), only shared?)

One major error that I am getting is in HttpConnectProxy.cs, inside the Connect() method override at line 75:
ProxyEndPoint.ConnectAsync( ProcessConnect, remoteEndPoint);

Error CS1929: 'EndPoint' does not contain a definition for 'ConnectAsync' and the best extension method overload 'SocketTaskExtensions.ConnectAsync(Socket, IPAddress, int)' requires a receiver of type 'Socket

Errors in Unity

Installing from nuget, the ScClient namespace is available in the C# environment and compiles success in the Visual Studio. But when run in the Unity, error occurs:
"Assets/Scripts/GameManager.cs(8,7): error CS0246: The type or namespace name `ScClient' could not be found. Are you missing an assembly reference?"

I have goooogled a lot, but still can't resolve it.
But there's something useful messages:
The unity doesn't support the DLL well, the DLL should be copy to Unity's assets Plugins folder.
I follow the step, but still get the following error info:
"Unloading broken assembly Assets/Plugins/ScClient.dll, this assembly can cause crashes in the runtime."

Any suggestions or if it possible to make a plugin to the Unity's asset store? It will be much easier to use in Unity.

Random error that crash application

{System.ArgumentException: An item with the same key has already been added. Key: 6
at System.Collections.Generic.Dictionary2[TKey,TValue].TryInsert (TKey key, TValue value, System.Collections.Generic.InsertionBehavior behavior) [0x000ad] in <d4a23bbd2f544c30a48c44dd622ce09f>:0 at System.Collections.Generic.Dictionary2[TKey,TValue].Add (TKey key, TValue value) [0x00000] in :0
at ScClient.Socket.Publish (System.String channel, System.Object data, ScClient.Emitter+Ackcall ack) [0x00075] in :0
at ScClient.Socket+Channel.Publish (System.Object data, ScClient.Emitter+Ackcall ack) [0x00001] in :0
at PrgName.MyListener.SendCordinate (System.Double lat, System.Double lon, System.Int32 carId) [0x0005c] in E:\localhost\PrgName\Helper\CommunicationHelper.cs:517 }

{System.ArgumentException: An item with the same key has already been added. Key: 2
at System.Collections.Generic.Dictionary2[TKey,TValue].TryInsert (TKey key, TValue value, System.Collections.Generic.InsertionBehavior behavior) [0x000ad] in <d4a23bbd2f544c30a48c44dd622ce09f>:0 at System.Collections.Generic.Dictionary2[TKey,TValue].Add (TKey key, TValue value) [0x00000] in :0
at ScClient.Socket.Emit (System.String Event, System.Object Object, ScClient.Emitter+Ackcall ack) [0x00053] in :0
at PrgName.Helper.MyListener.Login () [0x00034] in E:\localhost\PrgName\Helper\CommunicationHelper.cs:474 }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.