Debugging socket.io using Smart Websocket Client - node.js

I want to manual test my websocket funcstionality.I am using socket.io and just installed a chrome to extension which allows me to connect to my server and send messages to it.
After some research I found out the sceheme that socket.io uses to send messages - 42["{event}", {data}]
I must be doing something wrong because when I try to send this message I dont trigger my callback.
Here is my server side code:
import * as express from 'express';
import * as http from 'http';
import * as socketIo from 'socket.io';
import config from './config';
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// URL: ws://localhost:1337/socket.io/?EIO=3&transport=websocket
io.on('connection', function(client: socketIo.Client){
console.log('Client connected..');
io.on('auth', (data:any) => {
console.log(data);
});
});
//start our server
server.listen(config.port, () => {
console.log(`Server listening on port ${config.port}.`);
});
And here is the message which I am sending to my server.
42["auth","test"]
Here is a screenshot aswell.
I get the message when I connect to the websocket, but I cant trigger my callback for the 'auth' command.

I had the code wrong..
io.on('connection', function(socket:SocketIO.Socket){
console.log('Client connected..');
socket.on('auth', (data:any) => {
console.log(data);
});
});

Related

Connect to a third party server (twelvedata) from my own express server through web socket connection string

I want to connect to the twelevedata server through its provided socket connection to receive information.
import * as dotenv from 'dotenv'
import WebSocket from 'ws';
import express from 'express'
const app = express();
//setting up env
dotenv.config()
// setting up the websocket
const ws = new WebSocket(`wss://ws.twelvedata.com/v1/quotes/price?apikey=${process.env.API_KEY_TWELVEDATA}`);
const payload = {
"action": "subscribe",
"params": {
"symbols": "AAPL,INFY,TRP,QQQ,IXIC,EUR/USD,USD/JPY,BTC/USD,ETH/BTC"
},
}
ws.on('connection',function (steam) {
ws.on('open', (data) => {
console.log("data ==>",data);
ws.emit('subscribe',payload)
})
ws.on('subscribe', (data) => {
console.log("data ==>",data);
})
})
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`I am listening at ${port}`);
});
I created a websocket with my websocket connection on an express application but I am unable to receive any information from the twelvedata server regarding the subscribe event that I have emitted !
This is how the websocket should work as shown by the twelvedata website (look into the screen shots)
I am unable to connect and emit the subscribe event given by the twelvedata's documentation
You don't want to emit events from the websocket (that's for events you want to handle locally), but send, i.e., replace
ws.emit('subscribe',payload)
with
ws.send(payload)
// sending the parameters
ws.on('open', function open() {
ws.send(JSON.stringify(payload));
});
ws.on('message', function message(data) {
// receiving data
console.log('data ===>: ', JSON.parse(data));
});
ws.send did the charm for me

SocketIO send message to client via API route

I have a route in my express API where I want to emit messages using a websocket to a client. In this case, the client is another Node.js app. In this Node.js app, I try to connect to the socket and print messages received. Both the API and the Node app are on different ports. Can someone help me make this work?
Here's how I pass my socket to my express routes:
const server = app.listen(PORT, () => {
console.log(`Server on port ${PORT}`);
});
const io = require("socket.io")(server);
app.set("socketio", io);
Here's my REST API route:
exports.getAll = function(req,res){
var io = req.app.get('socketio');
io.emit('hi!');
}
Here's my socket io client, it uses socket.io-client
const socket = io('http://localhost:3000');
socket.on("message", data => {
console.log(data);
});
Unfortunately, I don't receive the 'hi' message from my API.
When I call /api/getAll I don't receive the message in my client app.
When emitting an event via socket.io you have you define the event name before the data.
Example:
exports.getAll = function(req, res){
var io = req.app.get("socketio");
io.emit("message", "hi!");
}
Now you'll be able to receive the message event from the client.
Reference:
https://socket.io/docs/v4/emitting-events/

Quasar application cannot connect to heroku socket.io server

I am trying to connect my quasar application to a socket.io express server hosted on heroku.
The problem is that every time I try to connect, the browser says the request is pending and on the backend I never receive the message of connection.
This is my backend code
const express = require('express');
const app = express();
const PORT = process.env.PORTA || 3000;
const server = app
.use((req, res) => {})
.listen(PORT, () => console.log(`Server is running on port ${PORT}...`));
const io = require('socket.io')(server, {
cors: {
origin: '*',
credentials: true
}
});
io.on('connection', socket => {
console.log('Connected: ' + socket.id);
});
And this is the connection in a boot file in quasar (vue.js) with socket.io extended
import Vue from 'vue'
import VueSocketIOExt from 'vue-socket.io-extended';
import { io } from 'socket.io-client';
const socket = io(URL_CONNECTION);
Vue.use(VueSocketIOExt, socket);
As you can see on the backend I have a console.log to see the id of the connected client. If I try this locally in my pc it works fine and I get the socket id, but on heroku the client doesn't connect without giving me any error.
I found a way to do this. I just removed the custom port I inserted in the server and I put the default (process.env.PORT) and then I connected from the client giving the port 80.
Now, I don't know why, but it's working.

ReactJS does not connect with NodeJS API using socket.io

I have an issue trying to connect a reactJS app with a nodeJS API using socket.io.
Here's API code :
const httpServer = require('http').createServer();
const io = require('socket.io')(httpServer);
httpServer.listen(8080, () => {
console.log('go to http://localhost:8080');
});
io.on('connection', socket => {
console.log('client connected');
});
And reactapp :
import React from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:8080";
function App(){
const socket=socketIOClient.connect(ENDPOINT);
return(<p>Hello</p>);
}
export default App;
As you can see, it is a simple code but still it doesn't work.
The 'client connected' message from the API never shows up.
It looks like the react app can't connect to the port even if it's open or idk.
It may happen because of syntax in the react app side. Can you try this one in the function?
function App(){
let socket = io(ENDPOINT, {
transports: ["websocket"],
});
console.log("Connecting...");
socket.on("connect", () => console.log("Connected!"));
}
or you can define socket outside of the function.

Nodejs Socket.io Express failed to handshake after calling HTTP API

I am using SocketIo with Nodejs, Express server and MongoDB, I followed the documentation . it works fine when connecting multiple clients they can send messages to each other without any problem . when I made an Http request, I cannot connect any new clients and get this error.
socket.io.js:7370 WebSocket connection to
'ws://localhost:28232/socket.io/?userId=userAmr&EIO=3&transport=websocket&sid=wNTTgrUD-PSeNaIcAAAF'
failed: Error during WebSocket handshake: Unexpected response code:
400
the other connected users before the Http request can continue sending messages without any problem.
I debugged the Socket library and found the client socket request go to connect function then fire errorCode:1
This this my code
/**
* Create Express server.
*/
const app = express();
// API endpoint
app.get('/api/test',(req,res)=>{
res.status(200).send({test:"test"});
});
/**
* Init socket
*/
// the following line not working too
// const server = require('http').createServer(app);
const server = require('http').Server(app);
const io = require('socket.io')(server);
io.on('connection', (socket) => {
// emit message to group
socket.on('emitMessage', (data) => {
io.emit('emitMessage', data);
});
});
The Client side code
import { Injectable } from '#angular/core';
import * as io from "socket.io-client/dist/socket.io.js"
import { BehaviorSubject } from 'rxjs';
#Injectable()
export class AppSocketService {
private url = 'http://localhost:28232';
private socket;
constructor() {
}
connect(){
this.socket = io(this.url,{
query:{userid:"123"},
forceNew:true,
'force new connection': true,
autoConnect: true,
reconnectionDelay: 1000,
timeout: 100000,
reconnectionDelayMax: 5000,});
this.socket.on('connect', () => {
console.log("connect",{"socketId":this.socket.id});
this.startListening();
});
}
startListening(){
this.socket.on('emitMessage', (data) => {
console.log(data);
});
}
emitMessage(message){
this.socket.emit('emitMessage', {message});
}
}
Client version:"socket.io-client": "^1.7.3"
Server version: "socket.io": "^1.7.3"
i found the problem, the package express-status-monitor making this wrong behavior .
try to remove it, and it will work perfectly
// comment these lines, as they making the issue
// const expressStatusMonitor = require('express-status-monitor');
// app.use(expressStatusMonitor());
The final code:
let app = require('express')();
// these two lines were making the problem, please comment them. if you want to reproduce the problem enable them again
// const expressStatusMonitor = require('express-status-monitor');
// app.use(expressStatusMonitor());
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.get('/api/v0/availabilities',(req,res)=>{
res.status(200).send({test:"test"});
});
io.on('connection', (socket) => {
// emit message to group
socket.on('emitMessage', (data) => {
io.emit('emitMessage', data);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});

Resources