question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Client not responding to hook

See original GitHub issue

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>

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:19 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
doghappycommented, Mar 16, 2020

The reason: When the server sends a buffer, the client will receive two messages.

  1. 451-[“message send”,{“_placeholder”:true,“num”:0}]
  2. byte array

The server code looks like this:

client.on('message send', data => {
    var buffer = Buffer.from("message send buffer string", "utf-8");
    client.emit("message send", buffer);
});

But this library is not implemented yet, A MessageEventBinaryParser should be added to the Parsers folder to capture messages starting with “451-”, also need to add a condition to read the buffer

else if (message.MessageType == WebSocketMessageType.Binary)

https://github.com/doghappy/socket.io-client-csharp/blob/526e954a89f3bcf9f83cc2dfbfbd3a3c0fe7dc74/SocketIOClient/SocketIO.cs#L123

I will try

0reactions
jrichardszcommented, Apr 14, 2023

I cannot emit a simple string 😦

<PackageReference Include="SocketIOClient" Version="3.0.8" />

Server : Linux + nodejs v16

const express = require('express');
const app = express()
const server = require('http').Server(app)
const io = require('socket.io')(server, { maxHttpBufferSize: 1e7 })

io.on('connection', function (socket) {
  console.log("headers at connection:")
  console.log(socket.handshake.headers)

  socket.on('hi', async function (msg) {
    console.log(">>>>>>>>>>>>>>"+msg.data);
  });

});

server.listen(3000)
console.log("Running on port: " + 3000)

c# Linux netcore 5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using SocketIOClient;
using System.Text;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("starting Program.cs");
        var client = new SocketIO("http://localhost:3000");   
        client.OnConnected += async (sender, e) =>
        {
            Console.WriteLine("Connected");
            await client.EmitAsync("hi", "im a simple string"); 
            Console.WriteLine("After send");            
        };
        await client.ConnectAsync();
    }
}

Logs

Client

Console.WriteLine("After send"); is not printed

image

server

Only the connected event is received

image

Read more comments on GitHub >

github_iconTop Results From Across the Web

Syncvar hooks not being called when running from server ...
SyncVar hooks don't fire on the server when the server changes the field. They only fire on the client when the client receives...
Read more >
React Hook error when calling the Apollo useQuery()
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of...
Read more >
Why can't I execute a client-side hook script when ...
To work around the issue, just commit the parent directory of the switch path rather than the switched path itself or a child...
Read more >
How to use handle hook on client side : r/sveltejs
Hello, is it possible to use handle hook on client side? I'm developing company's internal app so it's made as a SPA and...
Read more >
Hooks - Apollo GraphQL Docs
This property is part of Apollo Client's React integration, and it is not available in the core ApolloClient API. The default value is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found