Liam Hardy Liam Hardy - 1 month ago 52
C# Question

Csharp with node.js and socket.io

I wanted to send data from csharp to a webpage live without having to reload or anything annoying like that so I decided to use Node.JS and socket.io

I am totally new to socket.io and node.js so correct me if this isnt how it works...


1) I sent data from my Csharp application using the code below.

using Quobject.SocketIoClientDotNet.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Plus.HabboHotel.Roleplay.Extra.SocketIO
{
public static class SocketIOManager
{
public static void SendMessage(string message)
{
var socket = IO.Socket("http://127.0.0.1:400");

socket.On(Quobject.SocketIoClientDotNet.Client.Socket.EVENT_CONNECT, () =>
{
socket.Emit("emu_msg", @"Hello from PlusEMU");
socket.Disconnect();
});
}
}
}


2) The Node.JS app.js picks it up

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

io.on('connection', function(socket){
console.log('a user connected');
});

io.on('emu_msg', function(socket){
console.log('emu message received?');
});

http.listen(400, function(){
console.log('listening on *:400');
});


Now on the node.js console I should be getting "emu message received" should I not? I am not receiving that


Does anybody know why?

I do receive the 'a user connected' when visiting the webpage that uses the code below

<script>
var socket = io.connect('http://127.0.0.1:400');
socket.on('emu_msg', function(data) {
alert(data);
});
</script>


But when sending a message with csharp I don't get anything, not even the user connect message, am I missing something here? And I don't get the alert on the webpage when sending with csharp either.

Answer

on the client you should be listening for the message on the socket.

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('emu_msg', function(msg){
    console.log('emu message received?');
  });
});

see: here for more information