i followed instructions in this link Rohit Nishad and my data is well passed from client to server.
But the ID is not passed from my middleware with the overwritten function. A new Generated ID is shown on socket.io connection.
Any idea what's going wrong please ?
I'm using socket.io v3.1.0
server.js
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const socketIO = require('socket.io');
const io = socketIO(server, {
cors: {
origin: "http://localhost:4200",
methods: ["GET", "POST"]
},
});
// Socket.io configuration
io.of('/notification').use((socket, next) => {
console.log('(socket.handshake.query.userId) :', socket.handshake.query.userId);
io.engine.generateId = (req) => {
socket.handshake.query.userId;
};
next(null, true);
});
io.of('/user').use((socket, next) => {
io.engine.generateId = () => socket.handshake.query.userId;
next(null, true);
});
io.of('/notification').on('connection', socket => {
console.log('[Notification] - New client connected : ID ', socket.id);
});
io.of('/user').on('connection', socket => {
console.log('[User] - New client connected : ID ', socket.id);
});
const serverPort = process.env.PORT || port;
// Launch server
server.listen(serverPort, () => {
console.log(`App is running ! Go to http://${host}:${port}`);
});
and console output:
App is running ! Go to http://localhost:3000
(socket.handshake.query.userId) : 5ffdb966c204c85d4061bf9f
[Notification] - New client connected : ID EjdB0uz8K7NSGWYyAAAB
[User] - New client connected : ID E4tu9sKXliWTFEcsAAAC
Related
i'm developing a chat app in express by socket.io and this is my code:
well the front end cannot connect to socket io but server is running and i can login
const express = require("express");
const { Server } = require("socket.io");
const helmet = require("helmet");
const cors = require("cors");
const authRouter = require("./routes/authRouter");
const { corsConfig } = require("./controllers/serverController");
const {
Authorization,
AddFriend,
Disconnect,
dm,
} = require("./controllers/socketController");
require("dotenv").config();
const app = express();
const server = require("http").createServer(app);
const io = new Server(server, {
cors: corsConfig,
});
app.use(helmet());
app.use(cors(corsConfig));
app.use(express.json());
//! Routes
app.use("/auth", authRouter);
app.get("/", (req, res) => res.send("Hi"));
io.use(Authorization);
io.on("connection", (socket) => {
console.log("socket")
socket.on("add_friend", (friendName, cb) => {
AddFriend(socket, friendName, cb);
});
socket.on("disconnect", Disconnect);
socket.on("dm", (message) => dm(socket, message));
});
server.listen(5050, () => {
console.log(app.get("env"));
});
but my server isnt running on localhost:5050 this is the error i got :
curl "http://localhost:5050/socket.io/?EIO=4&transport=polling" curl: (7) Failed to connect to localhost port 5050: Connection refused
ive tried to change config of socket server but none of those worked
i have a socketjs file which will create my config and a useEffect hook which inside that ive tried to connect to my server
frontendCode:
socket.js
import { io } from "socket.io-client";
const socket = (user) =>
new io("http://localhost:5050", {
autoConnect: false,
withCredentials: true,
auth: {
token: user.token,
},
});
export default socket;
useSocket.js:
socket.connect();
socket.on("friends", (FriendList) => {
setFriendList(FriendList);
});
socket.on("messages", (messages) => {
setMessages(messages);
});
socket.on("dm", (message) => {
setMessages((prev) => [message, ...prev]);
});
socket.on("connected", (status, username) => {
setFriendList((prev) => {
const friends = [...prev];
return friends.map((friend) => {
if (friend.username === username) {
friend.status = status;
}
return friend;
});
});
});
socket.on("connect_error", () => {
setUser({ loggedIn: false });
});
returned error from frontend:
Firefox can’t establish a connection to the server at ws://localhost:5050/socket.io/?EIO=4&transport=websocket&sid=1uKM4znamAHH8P6kAAKY.
Hello everyone and happy holidays!
I'm creating a chat app using socket.io and Express and need some guidance on how to proceed.
As it is now, I have my socket.io module in the same file as my express js file.
And it works fine, but when I started to implement a login page i noticed that when a go to the "localhost:port/" i still get connected to the socket and i get assigned a socket.id.
And it does make sense, I suppose, to start from the top and go to the bottom.
My plan is:
Go through the login page first
Then get redirected to the "localhost:port/MessagingClient" and get a socket.id
How it works now:
Go to the login page, get assigned a socket.id without login in.
Go to "localhost:port/MessagingClient" and get assigned a new socket.id
But since i run everything in 1 js file it doesn't work as i want it to.
My question is how can I split "Login" page and "MessagingClient" page, but still run on the same port?
I imagine I could solve this by running 2 node js processes instead of 1 and use 2 ports, but is that a valid way of doing it?
MessaginServer.js:
const dotenv = require("dotenv").config();
const express = require("express");
const app = require("express")();
const http = require("http").Server(app);
const io = require("socket.io")(http);
const port = process.env.PORT || 3000;
// import { readFromDB } from "./mongoDB.js";
const { readFromDB } = require("./mongoDB");
app.use(express.static(__dirname + "/public/"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/Public/LoginClient.html");
});
app.get("/MessagingClient", (req, res) => {
res.sendFile(__dirname + "/Public/MessaginClient.html");
});
io.on("connection", async (socket) => {
// socket.on("test1", arr1, arr2)=>{};
// socket.on("test2", arr1, arr2)=>{};
})
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
What i have tried:
I tried to move all the socket.io code inside
app.get("/MessagingClient", (req, res) => {
res.sendFile(__dirname + "/Public/MessaginClient.html");
});
but that resulted in message duplication..
Then I thought about trying to use Npm concurrently, but could not find anything about whether it is okay to use it in a production environment.
Any tips?
you create a socket server in a separate file:
const socketServer = (server) => {
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
//set middleware for socket server here before .on
io.use((socket, next) => {
yourMiddleware(socket, next);
});
// your io connection logic
io.on("connection", async (socket) => {
// socket.on("test1", arr1, arr2)=>{};
// socket.on("test2", arr1, arr2)=>{};
});
};
module.exports = {
socketServer,
};
then in app.js
//initialize app
const app = express();
// add your middlewares and routing
const server = http.createServer(app);
// import socketServer
socketServer(server);
server.listen(PORT, () => {
console.log(`Server is listening on ${PORT}`);
});
you create a socket server in a separate file:
const socketServer = (server) => {
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
//set middleware for socket server here before .on
io.use((socket, next) => {
yourMiddleware(socket, next);
});
// your io connection logic
io.on("connection", async (socket) => {
// socket.on("test1", arr1, arr2)=>{};
// socket.on("test2", arr1, arr2)=>{};
});
};
module.exports = {
socketServer,
};
then in app.js
//initialize app
const app = express();
// add your middlewares and routing
const server = http.createServer(app);
// import socketServer
socketServer(server);
server.listen(PORT, () => {
console.log(`Server is listening on ${PORT}`);
});
I'm building a messaging feature with socket.io and a React frontend. With a socket.io only server it is working as expected, with the following code:
Socket.io server only
const io = require("socket.io")(5000, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
const id = socket.handshake.query.id;
socket.join(id);
socket.on("send-message", ({ recipients, text }) => {
recipients.forEach((recipient) => {
const newRecipients = recipients.filter((r) => r !== recipient);
newRecipients.push(id);
socket.broadcast.to(recipient).emit("receive-message", {
recipients: newRecipients,
sender: id,
text,
});
});
});
});
I am trying to integrate with express. The server is starting with the code below but messaging is no longer working:
Express server
const express = require("express");
const socketIo = require("socket.io");
const cors = require("cors");
const PORT = process.env.PORT || 5000;
const app = express();
const http = app.listen(PORT, () =>
console.log(`🚀 Server ready at http://localhost:${PORT}`)
);
const io = socketIo(http, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST", "send-message", "receive-message"],
},
});
io.once("connection", (socket) => {
const id = socket.handshake.query.id;
socket.join(id);
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
socket.on("send-message", ({ recipients, text }) => {
recipients.forEach((recipient) => {
const newRecipients = recipients.filter((r) => r !== recipient);
newRecipients.push(id);
socket.broadcast.to(recipient).emit("receive-message", {
recipients: newRecipients,
sender: id,
text,
});
});
});
});
Running it locally for both instances in Chrome with a window and another incognito window open on localhost:3000
As described here on('connection') event on client side not work. Change it to on('connect');
// server-side
io.on("connection", (socket) => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});
// client-side
socket.on("connect", () => {
console.log(socket.id); // x8WIv7-mJelg7on_ALbx
});
I have an Electron project initiated with VueCLI and a litle nodejs socket.io server, here's the server's file :
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers,
users
} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Run when client connects
io.on('connection', socket => {
console.log(`Connected tp ${socket.id}`)
app.get('/send-file', (req, res, next) => {
res.send('Sent')
})
socket.on('joinRoom', (args)=>{
console.log('joinroom')
})
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
});
});
const PORT = process.env.PORT || 7575;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
And here's my preload.js file :
const io = require('socket.io-client');
window.socket = io('http://localhost:7575');
window.socket.on('welcome', () => {
console.log('on welcome : welcome received renderer'); // displayed
window.socket.emit('test')
});
window.socket.on('error', (e) => {
console.log(e); // displayed ?
});
window.socket.on('ok', () => {
console.log("OK received renderer"); // displayed
});
window.socket.on('connect', () => {
console.log("connected renderer"); // displayed
window.socket.emit('test');
});
And here's my createWindow function:
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 700,
height: 600,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
enableRemoteModule: true,
preload: path.join(__dirname, 'preload.js')
}
})
win.setMenu(null)
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
}
The connection is made between the client and the server, because the console.log(Connected tp ${socket.id}) show a different socket ID everytime, but on my compenent, when I call the emit function nothing happens : window.socket.emit('joinRoom', {email:this.email, apikey:this.apikey})
And I can't event receive message on the client side, I've tested the server and everything works fine on a normale browser, but on my electron application can't emit or receive messages.
Is this related to my electron application?
Here's how I did it -
Server side:
const express = require('express')
const app = express()
// middlewares
app.use(express.static('public'))
// routes
app.get('/', (req, res) => {
res.render('index')
})
server = app.listen(7575, () => {
console.log("Server started");
})
//socket.io instantiation
const io = require("socket.io")(server)
//listen on every connection
io.on('connection', (socket) => {
console.log('New user connected');
//listen on "test"
socket.on('test', (data) => {
var username = data.username;
})
})
Client side:
socket = io.connect('http://localhost:7575')
socket.emit('test', {username: 'username'})
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");
});