Why is my socket.on callback function not working? - reactjs

On my client side in my function componet Join.js I want to use socket.on to generate a room id so I can have voice rooms. The problem is that I cant get either socket.on call to work on my client side.
join.js
.
.
.
const SERVER = "http://localhost:3001";
const socket = io.connect(SERVER);
const createSession = (room) => {
room.preventDefault();
socket.on('connect', () =>{
console.log('client socket.on')
} )
socket.on('create-session-response', session_ID => {
console.log(session_ID)
})
socket.emit("create-session", guest);
}
Server file
var express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
var cors = require('cors');
const http = require('http');
const socket = require('socket.io');
const server = http.createServer(app);
const io = socket(server, {
cors: {
methods: ['GET', 'POST'],
},
});
// Listening for incoming connections
io.on('connection', (socket) => {
clientObject = undefined;
socket.on("create-session", (data) => { createSession(socket.id, data)});
socket.on("connect", () => {console.log("server side")})
.
.
.
});
I get this error repeatedly in the browser console:
polling-xhr.js:157 GET http://localhost:3001/socket.io/?EIO=4&transport=polling&t=O2crGvY net::ERR_CONNECTION_REFUSED

Related

Getting error while integrating Socket io and cloudflare

Server-side code:
const express = require("express");
const app = express();
const http = require("http");
const { Server } = require("socket.io");
const cors = require("cors");
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log(`User Connected: ${socket.id}`);
socket.on("join_room", (data) => {
socket.join(data);
});
Client-side code:
import io from "socket.io-client";
const socket = io.connect("http://localhost:8080");
function App() {
const joinRoom = () => {
if (room !== "") {
socket.emit("join_room", room);
}
};
But getting the following error after hosting it to cloudflare which works fine in local.:
polling.js:311 GET http://localhost:8080/socket.io/?EIO=4&transport=polling&t=OKgPK3u net::ERR_CONNECTION_REFUSED
I tried giving different port but still facing the same problem. Can anyone please help me?

create Websocket with custom NextJS server

I'm runnung NextJS application with a custom server to establish a websocket between the frontend and the custom backend.
Here is the custom server:
const express = require("express");
const next = require("next");
const emitter = require("./lib/eventEmitter");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const server = express();
const http = require('http')
const socketIo = require("socket.io");
const wbServer = http.createServer(server)
const io = socketIo(wbServer);
io.on("connection", (socket) => {
console.log("client connected: ", socket.id);
});
app.prepare().then(() => {
server.all("*", (req, res) => {
return handle(req, res);
});
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});
});
Here is the frontend connection:
useEffect(() => {
(async () => {
let socket = io("http://localhost:3000");
socket.on("connected", () => {
console.log("Connected");
});
})();
});
but it's not connecting React is showing 404 error like this:
XHR GET http://localhost:3000/socket.io?EIO=4&transport=polling&t=ODFLYBM
[HTTP/1.1 404 Not Found 8ms]
The answer is listening to wbServer instead of server like this:
const server = require("http").Server(app);
server.listen(port, () => {
console.log(`> Ready on http://localhost:${port}`);
});

How to resolve the Socket.io error "ERR_NAME_NOT_RESOLVED

When I run my MERN Stack project on my localhost and get my app's render page, when I click on a button in my app, that button does and displays nothing. When I inspect my client-side render page, I see the following error:polling.js:311 GET http://%22http/socket.io/?EIO=4&transport=polling&t=O7Mtvxd net::ERR_NAME_NOT_RESOLVED. I don't know what it means, I searched the meaning on the internet but without success. Here is my backend index.js file:
const express = require('express')
const cors = require('cors')
const mongoose = require('mongoose')
require("dotenv").config()
const app = express()
const http = require('http')
const server = http.createServer(app)
const io = require('socket.io')(server)
const UserRoutes = require('./routes/User')
const AuthRoutes = require('./routes/Auth')
const PostRoutes = require('./routes/Post')
const PORT = process.env.PORT || 5000
const {MONGODB_URI} = require("./config")
app.use(cors())
app.use(express.json())
app.use((req, res, next) => {
io.req = req
req.io = io
next()
})
app.use('/api/auth', AuthRoutes)
app.use('/api/user', UserRoutes)
app.use('/api/post', PostRoutes)
require('./socket')(io)
mongoose
.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log('database connected')
server.listen(PORT, () => console.log(`server started on port ${PORT}`))
})
.catch((err) => console.log(err))
my backend socket.js file :
const User = require('./models/User')
const jwt = require('jsonwebtoken')
module.exports = (io) => {
io.on('connection', (socket) => {
if (io.req) {
socket.broadcast.emit('friend-login-status', { user_id: io.req.userId })
addSocketIdInDB(socket.id, io.req.userId)
socket.on('disconnect', () => {
socket.broadcast.emit('friend-logout-status', {
user_id: io.req.userId,
})
io.req.userId = null
})
}
})
}
async function addSocketIdInDB(socket_id, user_id) {
const user = await User.findById(user_id)
if (socket_id) {
user.socketId = socket_id
}
await user.save()
}
I looked on this question after this but without success. I work on Microsoft Edge .

Socket io working in localhost but when i deploy it it is doesn't work

Im building a scribblio clone everything works perfectly in localhost but when i deployed it to heroku it doesnt work : the server doesnt crash (i tried it by accessing a default route to check if it still working), also the the ui (react) works but the socket server doesnt send back data related to the game here are the files
connection in client (react):
import { io } from 'socket.io-client';
const IO = (playerName, picture, roomId, action) => {
// here in localhost i remplace it with http://localhost:3000
return io('https://name.herokuapp.com/', {
path: '/socket.io',
query: {
username: playerName,
picture: picture,
roomId: roomId,
action: action
}
});
}
export default IO;
server (index.js):
const express = require('express');
const http = require('http');
const socket = require('./util/socket');
const app = express();
const ioServer = new http.createServer(app);
socket.init(ioServer);
//To check if service is alive or not
app.get("/ping", (req, res) => {
res.send("pong");
});
/* other code */
ioServer.listen(process.env.PORT, () => {
consola.success(`Listening for sockets on port ${process.env.PORT}`)
});
util/socket.js:
const { Server } = require("socket.io");
const consola = require('consola');
const gameManager = require('./gameManager');
exports.init = (httpServer) => {
const io = new Server(httpServer, {
cors: {
origin: "*"
}
});
io.on('connection', socket => {
consola.info("Socket connected with " + socket.id);
let { username, roomId, action, picture } = socket.handshake.query;
username = username.substring(0, 18)
const room = new gameManager.Room({ io, socket, username, roomId, action, picture })
room.init(username);
room.listenCords();
room.listenToMessages();
/* other code */
});
/* other code */
}
Network tabs:
for both in localhost and hosted version i get this response and they are all the same only one of them :
network tab
in localhost i have this:
response in localhost
in the hosted version i get this:
response in hosted website

change code from template engine to next js

How do I convert my app that is made with .pug to next app ? I have an app using .pug engine and I want to convert it into next.
This is the app.js but as I know next is different how do I do it? Because here my files are in views, and in views the files are in pages etc how do I do it? Is there any way or I have to code it all again?
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
const middleware = require('./middleware')
const path = require('path')
const bodyParser = require("body-parser")
const mongoose = require("./database");
const session = require("express-session");
const http = require('http');
const server = app.listen(port, () => console.log("Server listening on port " + port));
const io = require("socket.io")(server, { pingTimeout: 60000 });
app.set("view engine", "pug");
app.set("views", "views");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
app.use(session({
secret: "#########",
resave: true,
saveUninitialized: false
}))
// Routes
const loginRoute = require('./routes/loginRoutes');
const registerRoute = require('./routes/registerRoutes');
const logoutRoute = require('./routes/logout');
const postRoute = require('./routes/postRoutes');
const profileRoute = require('./routes/profileRoutes');
const uploadRoute = require('./routes/uploadRoutes');
const searchRoute = require('./routes/searchRoutes');
const messagesRoute = require('./routes/messagesRoutes');
const notificationsRoute = require('./routes/notificationRoutes');
// Api routes
const postsApiRoute = require('./routes/api/posts');
const usersApiRoute = require('./routes/api/users');
const chatsApiRoute = require('./routes/api/chats');
const messagesApiRoute = require('./routes/api/messages');
const notificationsApiRoute = require('./routes/api/notifications');
app.use("/login", loginRoute);
app.use("/register", registerRoute);
app.use("/logout", logoutRoute);
app.use("/posts", middleware.requireLogin, postRoute);
app.use("/profile", middleware.requireLogin, profileRoute);
app.use("/uploads", uploadRoute);
app.use("/search", middleware.requireLogin, searchRoute);
app.use("/messages", middleware.requireLogin, messagesRoute);
app.use("/notifications", middleware.requireLogin, notificationsRoute);
app.use("/api/posts", postsApiRoute);
app.use("/api/users", usersApiRoute);
app.use("/api/chats", chatsApiRoute);
app.use("/api/messages", messagesApiRoute);
app.use("/api/notifications", notificationsApiRoute);
app.get("/", middleware.requireLogin, (req, res, next) => {
var payload = {
pageTitle: "Home",
userLoggedIn: req.session.user,
userLoggedInJs: JSON.stringify(req.session.user),
}
res.status(200).render("home", payload);
})
io.on("connection", socket => {
socket.on("setup", userData => {
socket.join(userData._id);
socket.emit("connected");
})
socket.on("join room", room => socket.join(room));
socket.on("typing", room => socket.in(room).emit("typing"));
socket.on("stop typing", room => socket.in(room).emit("stop typing"));
socket.on("notification received", room => socket.in(room).emit("notification received"));
socket.on("new message", newMessage => {
var chat = newMessage.chat;
if(!chat.users) return console.log("Chat.users not defined");
chat.users.forEach(user => {
if(user._id == newMessage.sender._id) return;
socket.in(user._id).emit("message received", newMessage);
})
});
})
If you don't want to refactor all your pug template engine pages to next.js pages, then you can make the pug pages coexist with the next.js. You can make the next.js the default route, and place next.js code after all pug page routes. And you also need to refactor app.get("/", middleware.requireLogin, (req, res, next) => {...} to make sure next.js is the default route.
To apply this rule, you need a custom next.js server.
sample code
const express = require('express');
const next = require('next');
const port = 3000;
const dev = process.env.NODE_ENV !== 'production'; // use default NodeJS environment variable to figure out dev mode
const app = next({dev, conf});
const handle = app.getRequestHandler();
const server = express();
// all your pug page routes should be declared before `server.get('*'`.
server.get('*', authMiddleware(false), (req, res) => {
// pass through everything to NextJS
return handle(req, res);
});
app.prepare().then(() => {
server.listen(port, (err) => {
if (err) throw err;
console.log('NextJS is ready on http://localhost:' + port);
});
}).catch(e => {
console.error(e.stack);
process.exit(1);
});

Resources