Coder Social home page Coder Social logo

socket.io-client-csharp's People

Contributors

23w avatar bitcoinbrisbane avatar crackxia avatar dependabot[bot] avatar derevnjuk avatar dmitrybk avatar doghappy avatar emanuel-v-r avatar futuristicoder avatar gilad-teller avatar giraffesyo avatar griffinsorrentino avatar jessekphillips avatar jlareo avatar muscla87 avatar sirdx avatar stfkolev avatar swuttich avatar tearth avatar thompson-tomo avatar vintageluke avatar yujianghao 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socket.io-client-csharp's Issues

Missing Buffers?

image

On the previous version this information was provided in Buffers, How do i retrieve this information in 2.0?

Ignore ssl certificate errors

Hello, is there any way to not verify the SSL certificate when using socket io troughth a SSL connection?
When I try I get the following errors:

System.Net.WebSockets.WebSocketException: 'Unable to connect to the remote server
HttpRequestException: The SSL connection could not be established, see inner exception.
AuthenticationException: The remote certificate is invalid according to the validation procedure.

How handle JSON ?

Server emit socket.emit("TEST", JSON.stringify({message: 'Test', status: 1})); . How parse to object in C#. Thanks

Backslashes crashing socket connection

I use socket.io to send json data via socket. There are combinations of backslashes that let the socket client crash.

This works:

    socket.emit('data', {
        "data": "test\\test"
    });

    socket.emit('data', {
        "data": "\\test"
    });

This data makes the client crash:

    socket.emit('data', {
        "data": "\\"
    });

    socket.emit('data', {
        "data": "test\\"
    });

Once I send a message with a trailing backslash the client spills "Websocket.Client.WebsocketClient|[WEBSOCKET CLIENT] Error while listening to websocket stream, error: 'Index was outside the bounds of the array.'"

Any chance to fix that? :)

OnClosed not invoked in Xamarin.iOS

I am referencing this package in a Xamarin.Forms project (chatbot application) which targets both Android and iOS. In Android all functionalities are working perfectly. In iOS, everything is working fine except one. After socket connection is successful (OnConnected is invoked and some messages are emitted and received), if I turn off wifi in iOS device to simulate loss of internet connection, OnClosed is not invoked. This gets invoked while running in Android though. Also, "State" has "SocketIOState.Connected" value. I tried with all nuget package versions from 1.0.2.6 to 1.0.3.8 (which is the latest stable version at this moment), since I saw some PRs mentioning OnClosed was fixed.

SocketIO.Connected is sometimes false right after "await SocketIO.ConnectAsync()"

If I have code like the following...

var io = new SocketIO(someOrigin);
io.OnConnected += (s, e) => { Console.WriteLine($"connected event, io.Connected={io.Connected}"); };

Console.WriteLine($"before ConnectAsync, io.Connected={io.Connected}");
await io.ConnectAsync();
Console.WriteLine($"after ConnectAsync, io.Connected={io.Connected}");

Then I will often get the following output...

before ConnectAsync, io.Connected=false
after ConnectAsync, io.Connected=false
connected event, io.Connected=true

Notice the io.Connected being false for the second output line even though we awaited for the completion of ConnectAsync, and we get confirmation that a connection did happen via the OnConnected event.

Callback in on()

Is there a way to call a callback function when the client receives a message?

For example in Javascript I can do the following:

socket.on('test', function (msg, cb) {
     cb('I received test');
}

Thanks in advance.

Ping Timeout on iOS device

Hi HeroWong,

Thank you for this great library!

We are working on a unity project that connects to a socket.io server (v2.3.0). The project runs fine in Unity simulator but when built to an iOS device, the connection is never made and the client is disconnected because of "ping timeout" OR "transport close" reasons.

We were wondering if you have any insight on what could be causing the issue.

Error messages aren't handled

When sending an error in a middleware with socket.io it isn't handled on the client.
The message type is: 44

An example of a middleware:

io.use((socket, next) => {
  if (/*check if authed*/) return next();
  next(new Error('Authentication error'));
}

Problem .net standard 2

Hi, thanks a lot.
I had a project on .net framework 4.5 and I have to use socket.io for connecting to server . I know .net standard 2 on .net framework 4.7 . Is there any way that I can use this package?

Error while stopping client, message: 'The WebSocket is in an invalid state ('Closed') for this operation. Valid states are: 'Open, CloseReceived

Hi,
I use the latest package version and after a few minutes I start receiving errors;

 [WEBSOCKET CLIENT] Error while stopping client, message: 'The WebSocket is in an invalid state ('Closed') for this operation. Valid states are: 'Open, CloseReceived''

please advice

private async Task InitMarketOrdersListener()
{
            try
            {
                _client = new SocketIO("https://socket.stex.com/");
                _client.On("App\\Events\\GlassRowChanged", res => { Console.WriteLine(res.Text); }, args =>
                {
                    lock (_locker)
                    {
                        HandleOrderItemChanged(args);
                    }
                });

                _client.OnConnected += async () =>
                {
                    var obj = new
                    {
                        channel = $"orderbook_data147",
                        auth = new { }
                    };

                    await _client.EmitAsync("subscribe", obj);
                };
 
                await _client.ConnectAsync();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to process order book items");
            }
 }

OnConnected never emits (or any other event) connecting to my WinSock2 server

Hey! I have my backend written in CPP and my frontend written in C# using your library for Websockets.

Whenever I'm trying to connect to my websocket server, the server logs that a new client has been connected but on the frontend the OnConnected event won't get dispatched, what can cause such a thing?

This is the server's code: https://gist.github.com/TheOnlyArtz/29c1ceb7fb769003cb5189f53abdd04d

And this is the frontend's code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SocketIOClient;

namespace Frontend.TriviaClient.Gateway
{
    class WSManager
    {
        public Client client;
        public SocketIO connection;

        public WSManager(Client c)
        {
            this.client = c;
        } 

        public async Task connect()
        {
            var socket = new SocketIO("http://localhost:1337");

            socket.OnConnected += Socket_OnConnected;
            await socket.ConnectAsync();
            Console.ReadLine();
        }

        private static async void Socket_OnConnected(object sender, EventArgs e)
        {
            Console.WriteLine("Connected!");
        }
    }
}

Allow us to set JsonSerializerSettings

image

I am working on developing a bot api for an app that tends to use a lot of nulls which is a headache to change all the classes at this point..., and I typically just ignore nulls with jsonserializersettings but now in V2, there is no way to ignore them, could you please add a way for me to set these settings?

transports?

not connectivity without transport error !!
to put into production, you don't even get a response from socketio server online !!!! localhost ok! not online production ?????

No overload matches delegate for Action

namespace Frontend.TriviaClient.Gateway
{
    class WSManager
    {
        public Client client;
       // public SocketIO connection;

        public WSManager(Client c)
        {
            this.client = c;
        } 

        public async Task connect()
        {
            var uri = new Uri("ws://localhost:1337");
            var socket = new SocketIO(uri);

            socket.OnConnected += Socket_OnConnected; // ERROR HAPPENS HERE
            await socket.ConnectAsync();
            Console.ReadLine();
        }

        private static async void Socket_OnConnected(object sender, EventArgs e)
        {
            Console.WriteLine("Connected!");
        }
    }
}

I've followed the samples in the repository.

Capturing events regardless of name

Hi,
I am developing a bot library that uses yours for connection. I have a functional requirement that I have a callback capturing all events regardless of their name, to support strongly-typed extensibility and DI.

The latest stable version has OnReceivedEvent, however it doesn't seem to capture binary events. Some of the events I need to capture are binary.

I upgraded to 2.0 alpha hoping it'd resolve the issue, but I see it no longer supports capturing all events at all. I have to register each event name with .On() method. Unfortunately, this would complicate my library code, and could potentially cause some runtime issues.

Is there a possibility to have OnReceivedEvent back, hopefully tweaked to capture all events, including binary ones?

Thank you in advance!

How to use Emit with callback?

Hi all :
I am your SocketIoClient User,
I follow your github test project and white some client/ server test case for testing .

Server: I add a server event in your socket.io-server.njsproj as follows:

    socket.on("v1/chat/enter", (msg2) => {
        console.log("v1");
        console.log(`${msg2.toString()}`);
        const binaryMessage2 = Buffer.from(msg2.toString() + " - server", "utf-8");
        socket.emit("v1/chat/enter", binaryMessage2);
    });

then I add 2 client test case:

Client Case 1:

     private readonly EventWaitHandle _waitsocketioconnected2 =
            new AutoResetEvent(false);
        [TestMethod]
        public async Task LocalEnterChatRoomTest3()
        {
            var client = new SocketIO(Uri, new SocketIOOptions
            {
                Query = new Dictionary<string, string>
                {
                    {"token", "io"}
                },
                ConnectionTimeout = TimeSpan.FromSeconds(10)
            });

            client.OnConnected += async (sender, e) => { _waitsocketioconnected2.Set(); };

            Stopwatch watch;

            _waitsocketioconnected.Reset();
            await client.ConnectAsync();

            _waitsocketioconnected.WaitOne(10000);

            Action<SocketIOResponse> reponseaction = async delegate(SocketIOResponse ack)
            {
                Trace.WriteLine("v1/chat/enter Ack.");
                await ack.CallbackAsync();
            };

            string Test = "DemoString";
            client.On("v1/chat/enter", reponseaction);

            await client.EmitAsync("v1/chat/enter", Encoding.UTF8.GetBytes(Test));
            //await client.EmitAsync("v1/chat/enter", reponseaction,Encoding.UTF8.GetBytes(Test));

        }

In Case 1, callback reponseaction will fire normally. But if I comment the following code:

            client.On("v1/chat/enter", reponseaction);
            await client.EmitAsync("v1/chat/enter", Encoding.UTF8.GetBytes(Test));

and replace them with :
await client.EmitAsync("v1/chat/enter", reponseaction,Encoding.UTF8.GetBytes(Test));

callback reponseaction will not fire. Can you help me to point out why the callback reponseaction will not fire when I use
await client.EmitAsync("v1/chat/enter", reponseaction,Encoding.UTF8.GetBytes(Test));

thanks a lot.
@doghappy

Can't emit JSON object

I'm having problem to emit JSON object to socket.io server.

If I send just a string... it works fine... very fine.

But when I try to emit JSON object, I have an error in server side. If I send the same JSON from angular client, there is no problem, therefore the issue is in the side of C# client.

I have tried in several ways:

Newtonsoft.Json.Linq.JObject json = new Newtonsoft.Json.Linq.JObject();
json.Add("uid", "e99a7b60-bdbb-11e9-a94b-005056c00001");
json.Add("name", "User A from client");

client.EmitAsync("user-logged", json.ToString());

Also as:

var serializer = new JsonSerializer();
var stringWriter = new StringWriter();
using (var writer = new JsonTextWriter(stringWriter))
  {
     writer.QuoteName = false;
     serializer.Serialize(writer, json);
  }
// Here i've tested with replace and without
string jsonStr = stringWriter.ToString().Replace("\"","'");
client.EmitAsync("user-logged", new StringContent(json.ToString(), Encoding.UTF8, "application/json"));

Can you provide a sample sending and receiving a JSON from socket.io

Thanks in advance

Ping pong and reconnect question?

I notice that if my client has run for several days then it will no longer receive new messages from socketio servers.

If on JS, I will create a 30s interval to ping the server ==> don't receive pong ==> Restart the connection.

But I have no idea on socket.io-client-csharp

  • Did socket.io-client-csharp already has built-in workaround?
  • Or I should I need to manually restart the connection like the JS approach?

Can anyone suggest me the workaround to ensure my client will not sleep & don't miss any message sent from the server?
Thanks.

Client stops pinging on reconnect

If the client loses internet connection long enough to get the "ClosedByServer" Disconnect event, the client will automatically reconnect after sometime when internet connection is restored, but when it reconnects the client does not ping which leads to a reconnect loop

System.Threading.Tasks.Extensions dependency error

Hi, many thanks for the library,
I've just installed [email protected] (runtime version is v4.0.30319) via NuGet, I could build it successfully.
But when I run the app, my app when crashed because of this error:

System.IO.FileNotFoundException: Could not load file or assembly 'System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Threading.Tasks.Extensions, Version=4.2.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
   at System.Threading.Channels.SingleConsumerUnboundedChannel`1..ctor(Boolean runContinuationsAsynchronously)
   at System.Threading.Channels.Channel.CreateUnbounded[T](UnboundedChannelOptions options)
   at Websocket.Client.WebsocketClient..ctor(Uri url, Func`3 connectionFactory)
   at SocketIOClient.SocketIO.ConnectAsync()
   at cBot.Robots.BitQSignalExecutor.<initRemoteSignal>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

The program try to load System.Threading.Tasks.Extensions, Version=4.2.0.0 but the installed version is System.Threading.Tasks.Extensions, Version=4.5.4, and release history has no version 4.2.0 !!

I'm using .NET 4.7.2 and add netstandard as reference.

here my code, copied from your example:

using System.Threading.Tasks.Extensions; // ==> VS IDE highlight that no Extensions in System.Threading.Tasks

   // --- here my class's function
    public async void initRemoteSignal()
    {
      const string TEST_CHANNEL = "chat_message";
      var client = new SocketIO("http://localhost:3000");
      client.ConnectTimeout = TimeSpan.FromSeconds(5);

      client.On(TEST_CHANNEL, args =>
      {
        string text = JsonConvert.DeserializeObject<string>(args.Text);
        Console.WriteLine(args.Text);
      });

      client.OnConnected += async () =>
      {
        for (int i = 0; i < 5; i++)
        {
          await client.EmitAsync(TEST_CHANNEL, i.ToString());
          await Task.Delay(1000);
        }
        await client.EmitAsync("close", "close");
      };
      client.OnClosed += Client_OnClosed;
      await client.ConnectAsync();
    }

I checked the project's references and sawSystem.Threading.Tasks.Extensions has already been there.

I think I got library interference issue, but I'm a new to C# .net so I dont know how to resolve this issue.
Any suggestion are welcome!

onDisconnected is never called

I have the problem that the OnDisconnected event is never called. Here my example code:

Client constructor:

this._socket.OnConnected += this.Socket_OnConnected;
this._socket.OnDisonnected += this.Socket_OnDisonnected;

Client Socket_OnDisconnect:

private void Socket_OnDisconnected(object sender, string e) {
     Logger.Log(LogLevel.Trace, "SocketIO Disconnect: " + e);
}

The OnConnected event is called but when I restart the socket server (Node.js) the OnDisconnect event is never called. Current version is 2.0.1-alpha.1.

Thanks in advance.

The WebSocket protocol is not supported on this platform

Hi @doghappy,
we use version 2.0.1 and still get the error on Windows 7 as described in closed issue #50.
I guess that issue should be reopened.
We cannot verify that it worked in a previous version (<2.0) and stopped working with the major rework in 2.0.0 or if it never worked, even with versions <2.0
Can you maybe explain the internals how socket.io-client-csharp is built up to get around the websockets requirement which is not included in Windows 7?
From the description from Microsoft I get that only abstract classes have been implemented for WebSockets in Windows 7:
https://docs.microsoft.com/en-us/dotnet/api/system.net.websockets.websocket?view=netcore-3.1
Can you explain how your library or System.Net.WebSockets.Client.Managed and System.Net.WebSockets.Client solve this issue?
Thank you very much in advance!

Client stops responding

I am having an issue where the client just stops working after about 60 seconds or less. No disconnect events are fired and no errors.

Client not responding to hook

SocketIOClient 1.0.3.3, .net core 3.1, C# 7.2

Summary:
Hooking into an existing service: https://wolflive.com that uses socket.io as their communication back end. SocketIOClient doesn't detect any of the "message send" events, however, a similarly setup javascript version does. I haven't been able to pinpoint the issue, however, I'm fairly certain it isn't something on my end. The example does detect "welcome" events, which is the weird thing.

I'm not sure what version of socket.io the server is on, but the working JS client is 2.3.0.

here is the C# code:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SocketIOClient;

public class Program
{

	static async Task Main(string[] args)
	{
		string email = args[0], pass = args[1];

		var url = "https://v3.palringo.com:3051";
		var io = new SocketIO(url)
		{
			Parameters = new Dictionary<string, string>
			{
				["device"] = "web",
				["token"] = Token()
			}
		};

		io.On("welcome", async (a) =>
		{
			Console.WriteLine("Welcome Result: " + a.Text);
			await io.EmitAsync("security login", new
			{
				body = new
				{
					username = email,
					password = pass
				}
			}, async (res) =>
			{
				Console.WriteLine("Login Result: " + res.Text);
				await io.EmitAsync("message group subscribe", new
				{
					headers = new
					{
						version = 3
					}
				}, (res) =>
				{
					Console.WriteLine("Msg subscribe: " + res.Text);
				});

				await io.EmitAsync("message private subscribe", null, (res) =>
				{
					Console.WriteLine("Msg DM subscribe: " + res.Text);
				});
			});
		});

		io.On("message send", a =>
		{
			Console.WriteLine("Message: " + a.Text);
		});

		io.OnConnected += () => Console.WriteLine("Connected");
		io.OnClosed += (a) => Console.WriteLine("Closed " + a.ToString());
		io.OnError += (e) => Console.WriteLine("Error " + e.Text);
		//io.OnReceivedEvent += (e, p) => Console.WriteLine("Recieved: " + e + ": " + p.Text);

		await io.ConnectAsync();

		Console.ReadLine();
	}

	private static string Token()
	{
		var Rnd = new Random();
		var d = DateTime.Now.GetTime();
		var uuid = "WExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".ToCharArray();
		var chars = "abcedf1234567890";

		for (var i = 2; i < uuid.Length; i++)
			uuid[i] = chars[Rnd.Next(0, chars.Length)];

		return string.Join("", uuid);
	}
}

Here is the working Javascript version:

<!DOCTYPE html>
<html>
<head>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
</head>
<body>
	<input type="email" id="email" />
	<input type="password" id="password" />

	<button onclick="login()">Login</button>

	<script>
		
		function generateToken() {
			var d = new Date().getTime();
			var uuid = 'WExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
				var r = (d + Math.random() * 16) % 16 | 0;
				d = Math.floor(d / 16);
				return (c == 'x' ? r : r & 0x3 | 0x8).toString(16);
			});
			return uuid; 
		}
		
		function init(email, pass) {
			//generate the session token
			var token = generateToken();
			//start socket
			var socket = io('https://v3.palringo.com:3051?device=web&token=' + token, {
				transports: ['websocket']
			});
			
			//Hook welcome
			socket.on('welcome', function(data) {
				console.log('welcome result: ', data);
				//send login
				socket.emit('security login', {
					body: {
						username: email,
						password: pass
					}
				}, function(res) {
					console.log('login result: ', res);
					//hook group messages
					socket.emit('message group subscribe', {
						headers: {
							version: 3
						}
					}, function(a) {
						console.log('Message Subscribe: ', a);
					});
					//hook private messages
					socket.emit('message private subscribe', null, function(b) {
						console.log('Message DM Subscribe: ', b);
					});
				});
			});
			
			//Hook messages
			socket.on('message send', function(data) {
				console.log('Message: ', data);
			});
			
			//Hook connected event
			socket.on('connect', function() {
				console.log('connected');
			});
			
			//Hook connection error
			socket.on('connect_error', function(error) {
				console.log('Connection error', error);
			});
		}
		
		function login() {
			var email = document.getElementById('email').value;
			var pass = document.getElementById('password').value;
			
			console.log('starting init');
			init(email, pass);
			console.log("init'd");
		}
		
	</script>
</body>
</html>

woops

Working now, ignore me. sorry.

SocketIO.State is always None

After calling ConnectAsync is executed successfully, the State is not updated to Connected. That's the reason Ping/Pong not call. And the result is no message anymore after some seconds.

Below is the code change I made in my local repository, and it works.
image

Client does not hook "on" event

When I listen an event with:

        // Listen server events
        client.On("ws_message-new", res =>
        {
            Console.WriteLine("WS from server" + res.Text);
        });

It does not work.

Issue (I think) it's related to line 186 in https://github.com/doghappy/socket.io-client-csharp/blob/master/SocketIOClient/SocketIO.cs:
...
else if (_parserRegex.IsMatch(text))
...

I see how message arrives ( in my sample, I receive: "42["ws_message-new","message from server"]" ), but it's not hooked by "on" method.

I use the following versions:
node: v10.16.0
socket.io: 2.2.0
express: 4.17.1

Callback is not called when EmitAsync is called on a connection with a Room

As explained in the title. I've already fixed the problem in your library and updated tests and server. Please if you can add me as Contributor I can push the branch with the fix and create pull request that you can evaluate to integrate in master.

This is the testcase that fails with the current version:

[TestMethod]
public async Task CallbackWithRoomTest()
{
	string text = string.Empty;
	string guid = Guid.NewGuid().ToString();
	var client = new SocketIO("http://localhost:3000/path");
	await client.ConnectAsync();
	await Task.Delay(1000);
	bool callbackCalled = false;
	await client.EmitAsync("callback", guid, async res =>
	{
		text = res.Text;
		callbackCalled = true;
		await client.CloseAsync();
	});
	await Task.Delay(1000);
	Assert.IsTrue(callbackCalled, "Callback was not called");
	Assert.AreEqual($"\"{guid} - server/path\"", text);
}

And don't forget to update the App.js on the node server to respond to the "callback" message on the Room "path":

client.on('callback', (data, fn) => {
        fn(data + " - server/path");
    });

Thank you

Some received socket.io callback packet not processed by library.

Hi : It's me again. @doghappy

First, thanks your quick response for my previous question.

I like your library and i use your library for my working project recently.

I have some issue about catch certain socket.io event's callback on the target server.

Please consider the following socket.io communication captured by fiddler:

csharp

in ID 10 and 11, i send a "v1/chat/enter" event packet to server, then server response ID 12~19

ID 14 and 15 are server "v1/chat/enter" event's callback response.

I use the following code snippet to catch the callback:

            Action<SocketIOResponse> reponseaction2a = async delegate (SocketIOResponse ack)
            {
                userEnterChatAck = EnterChatAck.Parser.ParseFrom(ack.InComingBytes[0].ToArray());

                msgcount = userEnterChatAck.Messages.Count;

            };
            await client.EmitAsync("v1/chat/enter", reponseaction2a, userEnterChatPacket.ToByteArray());

But i fail to catch it.

Then i write a node.js socket.io client by type script. below is my code snippet to catch "v1/chat/enter" callback:

            beanfunsocket.emit("v1/chat/enter", bfenterchateventbuffer , pbResultPayload => {

                console.log("enter chat callback.");
                var enterchatackresult = Beanfun.chat.v1.EnterChatAck.decode(pbResultPayload);

                var lastupdate = enterchatackresult.chatsLastUpdated;
                isenterchat = true;
                console.log("chat last update =" + lastupdate);

            });

Surprisingly, node.js socket.io client can catch the callback send by server.

below is success result screenshot.
csharp1

I try to trace into your library for days, but i failed to find a clue.
I suspect ID 14 and 15 are not received or processed by library.
but ID 14 and 15 are send by server indeed and received by my node.js socket.io client successfully.

Can you help me point out why my c# socket.io client fail to catch the ID 14 and 15 callback ?

I send my fiddler's packet capture file socketiocompare.saz as
attachment [fiddlerdata.zip](https://github.com/doghappy/socket.io-client-csharp/files/4902120/fiddlerdata.zip).
and I put fiddler setup in the attachment,too. you can install fiddler and double click socketiocompare.saz file,
then double click the request on the left panel to see detail communication info on "websocket" tab in right panel .

if you need any further info, please reply, i will respond asap.

thanks in advance.

about server send json string

my client get error json when i send json in my server,such as:
send {"code":200,"msg":"\u8fde\u63a5\u4e0a\u4e86","data":["acewdsfadas"]}
get "{\"code\":200,\"msg\":\"\u8fde\u63a5\u4e0a\u4e86\",\"data\":[\"acewdsfadas\"]}",
but when I use the js library it's normal.

Support windows7

SocketIOClient uses System.Net.WebSockets.ClientWebSocket as WebSocket client, but it does not support Windows 7.

System.Net.WebSockets.Client.Managed can make SocketIOClient run on Windows 7, but it causes new problems. When the server disconnects the WebSocket connection, ClientWebSocket.State is always Open

OnClosed does not work

Hi dogHappy... nice work

When I connect to server everything is ok, it connects, it emits, but when server disconnect the client, event onClose isn't fired.

.Net Framework support

Hello,

First, thanks for your work.

The project is currently only available for .NETStandard2.0. I'd like to have a version ready in NuGet that supports .net framework 4 and upper versions.
I did a little experiment, and it appears that your project could easily support it since everything works if we omit the WebSocketClient implementation.
How would you like to proceed? Create a new csproj that links to every files of SocketIOClient project but WebSocketClient.cs ?

I could create a pull request afterwards

Kind regards

OnClosed not working

Hi
I'm using your implementation in my unity project.it's works and I can connect to the server and can emit. but OnClose action not working well when server gets close can't detect the disconnection in the client but it works when I close the client app and I get this message "ClosedByClient".

Unable to send EmitAsync

Im unable to emit event, as the_namespace is null and i receive an exception

                   var client = new SocketIO("https://socket.stex.com/");
                 
                    client.On("App\\Events\\GlassRowChanged", res =>
                    {
                        Console.WriteLine(res.Text);
                    });
                    
                    client.OnConnected += async () =>
                    {
                        var obj = new
                        {
                            channel = "orderbook_data250",
                            auth = new { }
                        };
                        
                        client.EmitAsync("subscribe", obj).GetAwaiter().GetResult();
                    };
                   
                    client.ConnectAsync().GetAwaiter().GetResult();

Emit with callback

Right now "EmitAsync" accepts two parameters: "event" and "object".

Native implementation of method emit in socket.io is:

emit(event: string, payload?: any, callback?: Function): void

Is there any workaround to achieve the callback. Doing nothing, error: "TypeError: callback is not a function" is thrown in server.

Would it be possible to implement callback in EmitAsync ?

Thanks in advance

Add Header To Request

Thanks for This Library and it is really awesome and everything working correctly but i want to add a header to my request (emit) because i want to implement jwt auth token with my request to a specific function.
So is there is a way to add a header when i'm calling a function or not.
Thank You.

OnClosed not working on 1.0.3 and .Net Core

Hi,
I'm using your code on a dotnet core app but I could not make it work on version 1.0.3. When I downgraded it to 1.0.2.7 it worked fine. It can't detect the disconnection event.

Another issue I got was when I emit from the server something without data - like socket.emit("something").
It doesn't receive it.

Thanks

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.