GET /socket.io/?EIO=3&transport=polling&t=NZFvwqb 404 149 - node.js

I got the above exception when I try to implement socket.io to count active users, i tried every solution but nothing works for me.
Server:
const express = require("express");
const app = express();
const cors = require("cors");
const socketIo = require('socket.io');
const http = require('http');
//Enable CORS policy
app.use(cors());
app.options("*", cors());
//socket io
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origins: ["http://localhost:4200", "http://localhost:3000"],
methods: ["GET", "POST"],
credentials: false
}
});
var count = 0;
io.on('connection', (socket) => {
console.log("Client connected");
if (socket.handshake.headers.origin === "http://localhost:3000") {
count++;
socket.broadcast.emit('count', count);
socket.on('disconnect', () => {
count--;
socket.broadcast.emit('count', count);
});
}
});
//Server
app.listen(8080, () => {
console.log("Server is running on port 8080");
});

Change this:
app.listen(8080, () => {
console.log("Server is running on port 8080");
});
To this:
server.listen(8080, () => {
console.log("Server is running on port 8080");
});
You are facing this issue because the instance you've passed when initializing socket and instance you are listening to are different.
For more refer this:
Should I create a route specific for SocketIO?

Related

What is difference between socket and io in socket.io backend?

I am very new to this socket programming. I got confused when to use io and socket in below code. Here, when a new user connects to the server and listens to any events then we use socket.on for that but while sending back response we use io.emit, cant we use socket.emit here? and what is the difference between them?
const express = require('express');
const app = express();
const PORT = 4000;
const http = require('http').Server(app);
const cors = require('cors');
app.use(cors());
const io = require('socket.io')(http, {
cors: {
origin: "http://localhost:3000"
}
});
let users = [];
io.on('connection', (socket) => {
console.log(`⚡: ${socket.id} user just connected!`);
socket.on('newUser', (data) => {
users.push(data);
io.emit('newUserResponse', users);
});
socket.on('message', (data) => {
console.log(data);
io.emit('messageResponse', data);
});
socket.on('disconnect', () => {
console.log('🔥: A user disconnected');
users = users.filter((user) => user.socketID !== socket.id);
io.emit('newUserResponse', users);
socket.disconnect();
});
});
app.get('/api', (req, res) => {
res.json({
message: 'Hello world',
});
});
http.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});

Socket.io doesn't work with on event ("connection")

i want to use socket-io in my project and i established it on the server (node-js) and
the client (react) but it seems doesn't work fine and in console on the server i can't see user connected when user connected.
app.js (server):
const express = require("express");
const app = express();
const PORT = process.env.PORT || 5000;
(async () => {
await mongoConnect(error => {
if (error) {
console.log(error);
} else {
const server = app.listen(PORT, () =>
console.log(`server is running on ${PORT} port`)
);
const io = require("./utils/socket-io/socket-io").initialSocket(server);
io.on("connection", socket => {
console.log("user connected");
});
}
});
})();
socket-io.js (server):
const socketIo = require("socket.io");
let io;
module.exports = {
initialSocket: server => {
io = socketIo(server);
return io;
},
getIo: () => {
if (!io) {
throw new Error("no connection to socket-io");
}
return io;
}
};
posts.js (client):
import socketIo from "socket.io-client";
useEffect(() => {
socketIo("http://localhost:5000");
}, [socketIo]);
Edit your app.js to this
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app); // This is going to allow us to create a new web server for express and we're going to it to our express application
const io = socketio(server); // Configure socketio to work with a given server
// Now the server supports websockets
(async () => {
await mongoConnect(error => {
...
else {
io.on("connection", socket => {
console.log("user connected");
});
server.listen(port, () => console.log(`Server is up on port ${port}`));
}
});
})();

socket.io: Cross-Origin Request Blocked on Firefox

I'm running a nodejs socket.io server on a raspberry pi, and a socket.io web client on Firefox.
But Firefox keeps giving me a Cross-Origin Request Blocked (Same Origin Policy Error).
// nodeJS Server:
var app = require('express')();
var cors = require('cors');
app.use(cors({origin: '*:*'}));
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
io.on('connection', function(socket) {
socket.emit('announcements', { message: 'A new user jas joined!' });
});
//JS Browser client:
const socket = io('ws://<INSERT_MY_EXTERNAL_IP>:3000');
socket.on('connect', () => {
socket.send('Hello!');
});
I've also tried: io.origins(...), io.set("origin", ...), but those keep saying the functions origins and set are undefined.
Not sure what to do at this point.
You can pass in a cors prop when you initialize the server socket.
Pass in a config object with cors set to true, eg. cors: true or cors: { origin: '*' }.
Read more about that here.
In action (only tested in LAN):
client.js
const socket = io('ws://localhost:3000');
socket.on('testing', res => { console.log(res) });
server.js
const app = require('express')()
const server = require('http').createServer(app)
const opts = { cors: { origin: '*' } }
const io = require('socket.io')(server, opts)
const cors = require('cors')
app.use(cors())
io.on('connection', (socket) => {
console.log(`Client connected (id=${socket.id})`)
socket.emit('testing', 123)
socket.on('disconnect', () => {
console.log(`Client disconnected (id=${socket.id})`)
})
});
(
port => server.listen(
port,
() => console.log(`Express server running on port ${port}`)
)
)(3000)

How to fixed websocket invalid frame header?

I am running backend(nodejs server) at port 5000. And running frontend at reactjs.
Peerjs also not connecting. Everytime it throwing
WebSocket connection to
'ws://localhost:5000/socket.io/?EIO=3&transport=websocket&sid=RpMvIyH3kAFbQpntAAAA'
failed: Invalid frame header
I want keep frontend and backend in separate server.
Frontend(React)
try {
socket = io.connect('http://localhost:5000/');
} catch (e) {
console.error(e)
}
BackEnd(Nodejs)
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const { v4: uuidv4 } = require('uuid');
const { ExpressPeerServer } = require('peer');
const PORT = process.env.PORT || 5000;
const peerServer = ExpressPeerServer(server, {
debug: true
});
app.use('/peerjs', peerServer);
io.on('connection', (socket) => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId);
socket.to(roomId).broadcast.emit('user-connected', userId);
socket.on('message', message => {
io.to(roomId).emit('createMessage', message);
})
socket.on('disconnect', () => {
socket.to(roomId).broadcast.emit('user-disconnected', userId)
})
})
});
server.listen(PORT, () => {
console.log(`Server has started on port ${PORT}`);
});

Node net.Socket emit data to all connected clients

guys, I'm trying to make simple TCP server with net.Socket package I'm using the express framework.
The behaviour that Im trying to achieve is when user enters specific route to emmit data to all connected clients, doesn anyone now how could I achieve this ??
Here is my sample code:
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const net = require('net');
const PORT = 5000;
let connection;
const server = net.createServer((socket) => {
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
connection = socket;
});
app.use(cors());
app.use(bodyParser.json());
app.get('/', (request, response) => {
response.send('VMS server');
});
app.post('/contact', (req, res) => {
const data = { hello: 'hello' }
connection.write(data);
res.send({ data: 'data emmited' })
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
server.listen(1337, function() {
console.log("Listening on 1337");
});
The problem m having here is that data is gettings emitted multiple times, because Im assigning current socket to connection variable.
Is there any other way how I can do this, could I use server variable to emit to all connected clients somehow ?
Ok, managed to solve it. Here are steps on how I solved it - create an array of clients, & when a client connected to the server , push that socket to client array when disconnected remove that item from the array... And to emit data to all clients, I created a broadcast method where I loop through client array, and call the emit method of each socket & send data.
Here is a sample code:
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
const net = require('net');
const PORT = 5000;
let sockets = []; // array of sockets
// emmit data to all connected clients
const broadcast = (msg) => {
//Loop through the active clients object
sockets.forEach((client) => {
client.write(msg);
});
};
const server = net.createServer((socket) => {
console.log('CONNECTED: ' + socket.remoteAddress +':'+ socket.remotePort);
sockets.push(socket);
socket.on('end', () => {
console.log('DISCONNECTED: ');
// remove the client for list
let index = sockets.indexOf(socket);
if (index !== -1) {
console.log(sockets.length);
sockets.splice(index, 1);
console.log(sockets.length);
}
});
});
app.use(cors());
app.use(bodyParser.json());
app.get('/', (request, response) => {
response.send('VMS server');
});
app.post('/contact', (req, res) => {
const data = { hello: 'hello' }
broadcast(data); //emit data to all clients
res.send({ data: 'data emmited' })
});
app.listen(PORT, () => {
console.log(`Server running at: http://localhost:${PORT}/`);
});
server.listen(1337, function() {
console.log("Listening on 1337");
});

Resources