How to fixed websocket invalid frame header? - node.js

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}`);
});

Related

websocket not connecting to nextjs/express server

running into this error with socket.io + nextjs + custom express server:
WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: WebSocket is closed before the connection is established.
Server:
const { Server, Socket } = require("socket.io");
const express = require("express");
const { createServer } = require("http");
const next = require("next");
const { parse } = require("url");
const dev = process.env.NODE_ENV !== "production";
const PORT = process.env.PORT || 3000;
const user = require("./server/api/userAPI");
const game = require("./server/api/gameAPI");
const app = next({ dev });
const handle = app.getRequestHandler();
console.log("hello");
app
.prepare()
.then(() => {
const expressApp = express();
const httpServer = createServer(expressApp);
const io = new Server(httpServer, { transports: ["websocket"] });
expressApp.use(express.json());
expressApp.use("/user", user);
expressApp.use("/game", game);
expressApp.listen(3000, (err) => {
if (err) throw err;
console.log("> Ready on http://localhost:3000");
});
expressApp.get("*", (req, res) => {
return handle(req, res);
});
io.on("connect", () => {
console.log("socket connected");
const count = io.engine.clientsCount;
console.log(count);
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
});
here is the client:
useEffect(() => {
const socket = io("http://localhost:3000", {
// reconnectionDelay: 1000,
reconnection: true,
reconnectionAttempts: 10,
transports: ["websocket"],
agent: false,
upgrade: false,
rejectUnauthorized: false,
});
socket.on("connect", () => {
console.log("someone connected: ", socket?.id);
});
}, []);
never worked with websockets or a custom next server before, found this online which is similar to my issue but no luck: https://github.com/vercel/next.js/issues/30491
how can i get the socket to connect?

Flutter socket io doesn't connect to node js socket io server port 3000

NODE JS SERVER
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
io.on("connection", (socket) => {
console.log("connected");
/* console.log(socket) */
socket.on("msg", (msg) => {
console.log(msg);
});
Cars.watch().on("change", () => {
console.log("Something has changed");
Cars.find()
.sort({ date: -1 })
.then((items) => {
console.log(items);
io.emit("ucer", items);
});
});
});
server.listen(3000, () => {
console.log("listening on port 3000");
});
FLUTTER CLIENT SIDE
#override
void initState() {
super.initState();
initializeSocket();
}
void initializeSocket() {
print('initializeSocket');
IO.Socket socket = IO.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': false,
});
socket.connect();
}
When the initializeSocket function is run, the code execution without error while i was waiting for connection print in the terminal ,However print('initializeSocket') on the debug console.
heroku node js
flutter sockets
windows
use this ipv4 address to instead of localhost:3000 access in the mobile
Linux

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}`));
}
});
})();

SocketIO – connection issues and clustering

I have a really simple NodeJS app that I want to run on Heroku. This is how the index.js file looks like:
Server (port 3030)
const http = require('http');
const os = require('os');
const express = require('express')
const throng = require('throng'); // For cluster management
const { port, env, isProduction } = require('./config/vars');
const SocketIO = require('socket.io');
// Setting up a simple express app and wrapping it with http server
const setupServer = () => {
const app = express();
app.use(express.static(path.join(__dirname, '../public')));
const server = http.createServer(app);
return server;
};
const setupSocket = (server) => {
const io = new SocketIO(server);
io.on('connection', (socket) => {
console.log(`[Socket] Connection established: ${socket.id}`);
socket.on(msg.rooms.join, (room) => {
socket.join(room);
socket.to(room).emit(msg.rooms.joined);
console.log(`[Socket] User ${socket.id} joined '${room}' room`);
});
socket.on('disconnect', () => {
console.log(`[Socket] Distonnected: ${socket.id}`);
});
});
return io;
};
const WORKERS = (() => {
if (!isProduction) return 1;
return process.env.WEB_CONCURRENCY || os.cpus().length;
})();
async function master() {
console.log(`Preparing ${WORKERS} workers...`);
console.log('Master started.');
}
// There should be one server instance for each worker
const start = () => {
const server = setupServer(); // Returns and `http` server instance
const socket = setupSocket(server);
server.listen(port, async () => {
Logger.info(`Server – listening on port ${port}`);
});
return server;
};
const instance = throng({
workers: WORKERS,
lifetime: Infinity,
start,
master,
});
module.exports = instance;
Client (port 3000)
const setupSocket = ({ room }) => {
// Fallback if already setup
if (window.sockets[room]) {
return window.sockets[room];
}
const socket = io('http://localhost:3030');
socket.on('connect', () => {
console.log('[Socket] Connection established!', socket.id);
socket.emit('room.join', room);
});
socket.on('room.joined', () => {
console.log(`[Socket] Connected to ${room} room!`);
});
window.sockets[key] = socket;
return socket
};
The problem – the connection is sometimes established properly but most of the time I get an error
Error during WebSocket handshake: Unexpected response code: 400
What might be the problem here? Is it because I have it on two different ports or is it because of the clusters?
I've tried removing the throng part of the code, and just calling start() method without any cluster setup, but the problem remains :(
why would you use http module? The server instance that you send in the socketIO constructor should be the return object of the expressInstance.listen
Something more like this:
const express= require('express')
const app = express()
const socketio = require('socket.io')
app.use(express.static(__dirname + '/public'))
const server = app.listen('4000',()=>{
console.log('Listening to port:4000')
})
const io = socketio(server)
io.on('connect',(socket)=>{
socket.broadcast.emit('new_user')
socket.on('new_message',(message)=>{
io.emit('new_message',message)
})
})
source code: socket-io chat

Socket.io in server gets disconnect repeatedly while on client side doesn't

I am going to make a private chat app like WhatsApp.
I connect to the server successfully
but the socket after several seconds gets disconnect from the server.
while on the client it doesn't disconnect.
Server code:
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
const onlineusers = {};
const socketid = {};
io.on('connection', cs => {
cs.on('online', username => {
if(username){
onlineusers[username] = cs.id;
socketid[cs.id] = username;
}
console.log("\nonline: ", onlineusers);
});
cs.on('disconnect', () => {
delete onlineusers[socketid[cs.id]];
console.log("\noffline: ", onlineusers);
});
});
const chat = io.of("/chat");
chat.on('connection', cs => {
cs.on('startchat', username => {
if (username){
chat.to('/chat#'+onlineusers[username]).emit('hey', 'I love programming');
}
});
});
server.listen(port, err => {
if(err){
console.error("Some Error: "+err);
}else{
console.log(`Server is running on port: ${port}`);
}
});
MY CLIENT code is by react-native and socket.io-client:
On line users file:
import io from 'socket.io-client';
const SocketEndpoint = 'http://192.168.43.172:3000';
this.socket = io(SocketEndpoint, {
transports: ['websocket']
});
this.socket.on('connect', () => {
if (this.state.username) {
this.socket.emit("online", this.state.username);
}
});
this.socket.on('connect_error', (err) => {
Alert.alert(err);
});
this.socket.on('disconnect', () => {
Alert.alert('disconnected');
});
Chat page file:
import io from 'socket.io-client';
const SocketEndpoint = 'http://192.168.43.172:3000/chat';
this.socket = io(SocketEndpoint, {
transports: ['websocket']
});
this.socket.on('connect', () => {
if (theirusername) {
this.socket.emit('startchat', theirusername);
}
this.socket.on('hey', data => {
alert(data);
});
this.socket.on('janajan', data => {
alert(data);
});
});
I want to keep to client socket on the server until the client themselves gets the disconnect.
because here when I want to say hey it gets a disconnect and my message could pass to the client.
thank you before

Resources