I'm learning socketIO
and I set up and running a basic nodejs
server . My problem is that when I try to connect to the server with my nextJS
app nothing happens. No errors occur and the messages I want to be printed on connection do not appear .
My code :
server.js
in backend folder
const express = require('express');
const app = express();
const server = require('http').Server(app);
const { v4: uuidV4 } = require('uuid');
const cors = require('cors');
const io = require('socket.io')(server, {
cors: true,
origins:["http://localhost:3000"]
});
app.use(cors());
app.options('*', cors());
io.on('connection', socket => {
socket.on('test',()=>{
console.log(' i am a test') //does not appear
})
})
//I ALSO TRIED
//io.on('test',()=>{
//console.log('I am a test');
//})
server.listen(5000);
Then in my nextJS app in my frontend folder in index.js
import {useEffect} from 'react';
import io from 'socket.io-client';
const ENDPOINT = "http://localhost:5000";
const socket = io.connect(ENDPOINT);
export default function Home() {
useEffect(()=>{
socket.emit('test');
},[]);
...rest of code
}
So in my frontend app I emit the 'test' event to the server and the server did not console.log the response on connection
I would appreciate your help as I am new to socketIO
CodePudding user response:
You can create a helper function in a separate file to manage the connections, listen to events and emit events. Here is one example for same :
export const socketConnection = io => {
io.on("connection", socket => {
console.log("Started socket connection!");
socket.on("message", receivedMessage => {
console.log("Socket message received", receivedMessage);
});
socket.on("subscribe", async room => {
try {
console.log(`In room`, socket.rooms);
await socket.join(room);
console.log(`[socket] Room Joined Successfully : ${room}`, room);
await io.to(room).emit("subscribeSuccess", `Subscribed successfully ${socket.id}: room - ${socket.rooms}`);
} catch (e) {
console.log(`[socket] Error in Room Joining : ${room} : ${e}`, e);
socket.emit("error", "couldnt perform requested action");
}
});
socket.on("unsubscribe", async room => {
try {
await socket.leave(room);
console.log(`[socket] Room Left Successfully : ${room}`, room);
} catch (e) {
console.log(`[socket] Error in Room Leaving : ${room} : ${e}`, e);
socket.emit("error", "couldnt perform requested action");
}
});
});
};
And then in app.js
you can import and start a socket server.
import { socketConnection } from "@helpers";
const io = new Server(server, {
transports: ["websocket", "polling"],
allowEIO3: true
});
socketConnection(io);
And to connect to socket from client use this :
import io from 'socket.io-client';
const ENDPOINT = "http://localhost:5000";
const socket = io(ENDPOINT);