hyprstack
hyprstack

Reputation: 4229

ExpressJs - SocketIo.client - emit not working

I am trying to connect to the crypto compare's api websockets to get the up to date prices for crypto currencies. I am using expressjs for my server and socketio to connect to crypto compare. However after logging connected nothing else seems to happen. This is my first time trying to play with sockets so I am a little lost as to why the io.emit function is not triggering anything. Also there seems to be an issue in the callback of connect as socket is undefined!

Why does emit not seem to be doing anything?

My app.js file:

const express  = require('express');
const app      = express();
const clientIo = require('./lib/client-socket/crytpto-compare-socket');

clientIo.connect();

app.disable('x-powered-by');

module.exports = app;

Crypto-compare-socket.js

const io      = require('socket.io-client');
const configs = require('./../config/configs');

const crytpCompareConfigs = configs.get('CRYPTO_COMPARE_API');
const cryptoCompareEndpoint = crytpCompareConfigs.ENDPOINT;

const cryptoCompareSocket = io(cryptoCompareEndpoint, {reconnect: true});

cryptoCompareSocket.on('connect', (socket) => { // socket here is undefined
  console.log('Connected');
  cryptoCompareSocket.emit('SubAdd', { subs: crytpCompareConfigs['LIST_OF_ITEMS']});
});

cryptoCompareSocket.on('SubAdd', (from, msg) => {
  console.log('Hello');
  console.log(from);
  console.log('*******');
  console.log(msg);
});

module.exports = cryptoCompareSocket;

Upvotes: 1

Views: 93

Answers (1)

Joshua Leonard
Joshua Leonard

Reputation: 512

The code you are using is client side code. This code does not return a socket in the callback because the client already knows the socket its connected with.

You are subscribing to a socket service, but you do not have any code that responds to data sent from that service.

When crypto compare returns data it sends the "m" event. So you need to respond to "m".

An example

cryptoCompareSocket.on("m", function(message) {
     console.log(message);
    });

Upvotes: 2

Related Questions