socket.io client not firing events on socket io server - javascript

I have built a backend and wanted to test it with some front-end code but for whatever reason, it is just not firing the events on the server. I dont get the "on connect" event triggered. I already downgrade the backend to a version similar to my testing script but still all the server shows, are logs like this.
[22/Oct/2021:14:06:21 +0000] "GET /socket.io/?EIO=4&transport=polling&t=NoeKlFT&b64=1 HTTP/1.1" 404 149 "-" "node-XMLHttpRequest"
I am using socket io for server and client version 3.1.2
Here is the backend code snippet
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const morgan = require("morgan");
const cors = require("cors");
const config = require("./src/config/general");
const exchangeController = new ExchangeController(io); // I want to pass in the IO obejct to be able to deal with all the event stuff in another file besides the apps entry point file.
Here is the part where I want the IO object to be available and work with the events from there
class ExchangeController {
constructor(io) {
this.io = io;
this.exchangeService = new ExchangeService();
this.router = express.Router();
this.initRoutes();
this.io.on("connection", (socket) => {
console.log("incoming socket connection"); //gets never logged to console when connecting frontend
//do further stuff (deleted for post)
});
});
}
This is the frontend script for testing the connection
//client.js
const io = require('socket.io-client');
const socket = io("mysecreturl") //also tried localhost instead of deployed app url no difference
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
I really tried for way too long now without getting any results. I hope you guys can guide me on the right path again.
Cheers

Related

Cannot connect socket.io to frontend javascript file

I am developing a website that needs to catch events emitted from server.js into a javascript file that handles the frontend. Obviously I am using socket.io (i said that in the title) and the method I am using to connect the backend and the frontend is the following:
<script src="/socket.io/socket.io.js"></script>
<script src="js/chat.js"></script>
Then in the chat.js file i just decalre a const like this:
const socket = io();
and then I use the method
socket.on('event', (data) =>{
});
eccc...
This method does not seem to work though.
It says: Failed to load resource: the server responded with a status of 404 (Not Found).
(Also says that io is not defined but it's normal if it cannot find the socket.io file).
I have followed a tutorial that has done the same and it does not work anymore as well.
On my server.js the code looks like this:
const mongoose = require('mongoose');
const connectDB = require('./config/dbConnection');
const express = require('express');
const app = express();
const path = require('path');
const http = require('http');
const server = http.createServer(app);
const socketio = require('socket.io');
const io = socketio(server);
const fsPromises = require('fs').promises;
const bodyParser = require('body-parser');
const User = require('./model/user');
const moment = require('moment');
const PORT = process.env.PORT || 3500;
Thanks to anyone who answers.

How to connect to a nodejs socket server?

I am new to node JS and I am trying to create a real time application that consists of a node JS server with socket.io and a unity application that can connect to it
I created the server with the sockets in the below code :
const express = require('express');
const http = require('http');
const app = express();
const port = process.env.PORT || 9000;
const server = http.Server(app);
const io = require('socket.io')(server);
io.on('connection',(socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
})
app.get('/',(req,res) =>{
res.json({worked : 'worked'});
});
server.listen(port,() => console.log(`Listening on localhost ${port}`));
I can connect to the socket server via the nodejs client files using socket.io-client
<script>
const socket = io('http://localhost:9000');
socket.on('message',(message) => console.log(message));
</script>
But the problem is whenever I try to connect from a different client I don't receive anything in the console.
I tried to use Smart Web Socket client to debug what's happening but whenever I connect (try to)
this happens
Any help would be much appreciated and thanks in advance
So if anyone stumbles in this thread I was able to fix the problem by installing the latest version of socket.io (^3.1.0) and allowing the EIO3 connections

socket.io with express slows down after amount of request from react client

I have built a React app that is connected to a local running express node server with socket.io. Everything works fine but after a few hours of 100+ sending requests, and listening to those changes from the local server to the client it starts to slow down and won't work as efficiently until I reload the client window sessions.
I have a very difficult time troubleshooting this. Do you think it has something to do with my node server setup, or is it something with my client? Or maybe it's hardware issues? One thing I notice is that how my client keeps connecting to socket.io from the console.
const express = require('express')
const http = require('http')
const socketIO = require('socket.io')
// localhost port
const port = 4001
const app = express()
// server instance
const server = http.createServer(app)
// creates socket
const io = socketIO(server)
io.on('connection', socket => {
socket.on('change view', (view) => {
console.log('view changed to: ', view)
io.sockets.emit('change view', view)
})
})
server.listen(port, () => console.log(`Listening on port ${port}`));
React app client side:
componentDidMount() {
const socket = socketIOClient(this.state.endpoint);
socket.on('change view', (col) => {
callAfunctionThatDoesSomething(col);
})
};
When I send changes to the server
send = () => {
const socket = socketIOClient(this.state.endpoint);
socket.emit('change view', this.state.view);
}
Any ideas?
You are connecting to socket.io two times. First at componentDidMount and second, when calling send(). Which is not recommended.
You should connect to socket one time. You can connect in componentDidMount method of a component. But if you want to use socket in multiple component. This will also connect to socket multiple time.
I will say you connect to socket one time when registering routes or your whole app. I created a sample app before. You can check it.
https://github.com/vkasraj/random.ly

Nuxt JS with WebSockets

I have a Nuxt App, with one service which needs to be delivered over WebSockets. The Nuxt App Server provides an api service using express.
I have an /api folder in which there are various *.js files, and these are routed to successfully. ie...
const express = require('express');
const app = express();
app.get('/whatever1',(req, res) => console.log('req.url',req.url))
works OK.
However the following, in the same file, will never be reached....
const express = require('express');
const app = express();
const expressWs = require('express-ws')(app);
app.ws('/whatever2',(ws,req) => {
console.log('req.url',req.url);
})
Where am I going wrong ?
You're attempting to connect the client to an endpoint on the server where no such endpoint exists. In your client's output, you're receiving an error of:
VM1295:1 WebSocket connection to 'ws://localhost:3000/api/whatever2' failed: Connection closed before receiving a handshake response
because you haven't defined a route of /api/whatever2. Your code above routes to:
ws://localhost:3000/whatever2
instead of ws://localhost:3000/api/whatever2
EDIT:
Here's test code that worked for me:
const express = require('express');
var app = express();
const expressWS = require('express-ws')(app);
expressWS.getWss().on('connection', function (ws) {
console.log('connection open');
});
app.ws('/whatever', (ws, res) => {
console.log('socket', ws);
});
app.listen(3000, () => console.log('listening on 3000...'));

Socket.io with express backend

I want to implement socket.io on my express backend to inform the user about the task's state during the request (state is like started, processing, ...)
So, user clicks a button, socket connection opens and waits for events, during long running request backend emits data to client and finally response comes and request finishes, the result is shown to user.
in my index.js file, which I bootstrap the application
const express = require('express'),
app = express(),
router = require('./router'),
server = require('http').Server(app);
var io = require('socket.io')(server);
/* other required modules*/
server.listen(config.port,'127.0.0.1');
router(app, io);
in my router.js
const taskController = require('./controllers/task');
/* other required modules*/
module.exports = function(app, io) {
const apiRoutes = express.Router();
apiRoutes.post('/task/do', taskController.doTask(io));
}
in my task.js
exports.doAnalysis = function(socket){
return function(req, res){
socket.emit('task-start', 'Your task is started');
...
}
}
When I do this, it emits all the connected clients.
What I want to do is, emit from my controller's functions to only specific client which calls the endpoint so, sender only.
Also, I can't do in my task controller the following snippet:
exports.doTask = function(socket){
return function(req, res){
socket.on('connection', function(s){
s.emit('task-start', 'Your task is started');
...
})
}
}
Apparently, passing io object won't work for this scenario.
I know that I should get all socket ids and emit with specific socket id but,
what is the proper way to do this ?

Categories