What is difference between socket and io in socket.io backend? - node.js

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

Related

Error while getting message from Server end in Transport Polling Error With Socket

Hello I am trying to build Chat Application, but my issue with socket.io, first
<script src="socket.io/socket.io.js"></script>
is not found, if i am using
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js" integrity="sha384-/KNQL8Nu5gCHLqwqfQjA689Hhoqgi2S84SNUxC3roTe4EhJ9AfLkp8QiQcU8AMzI" crossorigin="anonymous"></script>
then its working fine for me only one way conection, but
http://127.0.0.1:3000/socket.io/?EIO=4&transport=polling&t=OJDCcA5
this is not found.
Server.js
var express = require('express');
var cors = require('cors');
var mongoose = require('mongoose');
var app = express();
var http = require('http').Server(app);
app.use(cors());
var server = app.listen(3000, () => {
console.log("server is running on port", server.address().port);
});
var io = require('socket.io')(http);
//Connection Mongo Database with Mongooes
var dbUrl = 'mongodb://127.0.0.1:27017/ChatApplication';
mongoose.connect(dbUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
}, (err) => {
if(err){
console.log('Mongodb Not Connected',err);
}
});
var connection = mongoose.connection;
console.log(mongoose.connection.readyState); //logs 0
mongoose.connection.on('connecting', () => {
console.log('connecting')
console.log(mongoose.connection.readyState); //logs 2
});
mongoose.connection.on('connected', () => {
console.log('connected');
console.log(mongoose.connection.readyState); //logs 1
});
mongoose.connection.on('disconnecting', () => {
console.log('disconnecting');
console.log(mongoose.connection.readyState); // logs 3
});
mongoose.connection.on('disconnected', () => {
console.log('disconnected');
console.log(mongoose.connection.readyState); //logs 0
});
connection.once("open", function() {
console.log("MongoDB database connection established successfully");
});
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}))
var Message = mongoose.model('message',{ name : String, message : String})
console.log(Message);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/messages', (req, res) => {
console.log("Message Recived");
Message.find({},(err, messages)=> {
res.send(messages);
})
})
app.post('/messages', (req, res) => {
var message = new Message(req.body);
//console.log(message);
message.save((err) =>{
if(err)
sendStatus(500);
io.emit('message', req.body);
res.sendStatus(200);
})
})
io.on('connection', () =>{
console.log('a user is connected')
})
//https://masteringjs.io/mongoose
//https://www.freecodecamp.org/news/simple-chat-application-in-node-js-using-express-mongoose-and-socket-io-ee62d94f5804/
Please let me know, where do i am wrong.
Trying to Real time message get from server end using socket.

My socket event don't trigger when I am emit it in Nodejs

My socket event doesn't trigger when I emit it in Nodejs, I know it because I don't see "Pizza" in my console.
This is my code:
const express = require("express");
const cors = require("cors");
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
});
app.use((req, res, next) => {
req.io = io;
next()
})
app.use(cors());
io.on('connection', (socket) => {
socket.on("dummy_event", (data) => {
console.log(`Socket 🍕`); // I don't see this message in my console
if(!data.name) return;
})
});
app.get("/socket_test", (req, res) => {
req.io.emit("dummy_event", {name: "pizza"})
return res.json({data: 'dummy text'})
})
server.listen(4000, () => {
console.log(`Server Started on Port 4000`);
})

Socket connection is not working while using express with next.js

I have a problem with using socket.io in my application.
I use Next.js, Express.js, socket.io, socket.io-client
When I run Next.js server and Express server then access the page, socket is immediately connected. But when I post to /webhook/notify from other server socket.emit("notify", req.body); does not work. But when I reload the backend server, somehow it works for no reason.
Below are my codes
Frontend side
const socket = io.connect("http://127.0.0.1:3000", { cors: true }); //backend server
socket.on("connection", async (data) => { // it works
try {
console.log(data);
} catch (err) {
console.error(err.response);
}
});
socket.on("notify", async (notify) => { // it does not works while I reload backend server
try {
console.log(notify);
} catch (err) {
console.error(err.response);
}
});
Backend side
index.js
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors({ origin: "http://127.0.0.1:3060" }));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
const Socket = require("./socket");
const server = app.listen(PORT, function () {
return console.log("Backend server listening on port" + PORT);
});
Socket(server, app);
socket.js
const Socket = require("socket.io");
const axios = require("axios");
module.exports = (server, app) => {
const io = Socket(server, {
cors: {
origin: "*",
},
});
io.on("connection", (socket) => {
console.log("socket is connected");
app.post("/webhook/notify", (req, res, next) => {
try {
socket.emit("notify", req.body);
} catch (err) {
console.error(err.response);
return next(err);
}
});
socket.on("disconnect", () => {
console.log("disconnected");
});
});
};

Socket.IO and Electron can't emit or receive

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'})

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