How to send message to frontend in case of MongoDb connection Failed - node.js

Is there any way to send error to frontend on mongoDb connection error.I had tried in a different different way but I didnt get a solution.
var express = require('express');
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
app.get('/',function(req,res){
res.send('NOT Connected....')
});
});

You can use web sockets to push this information to the UI.
const express = require('express');
const app = express();
const path = require('path');
const server = require('http').createServer(app);
const io = require('../..')(server);
const port = process.env.PORT || 3000;
var session = require('express-session');
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore(
{
uri: config.connectionString,
collection: 'tbl_session'
});
// Catch errors
store.on('error', function(error) {
socket.emit('mongodb-failed', error)
});
});
server.listen(port, () => {
console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', (socket) => {
// when socket emits 'mongodb-connection-failed', this listens and executes
socket.on('mongodb-failed', (data) => {
// we tell the client to execute 'new message'
socket.broadcast.emit('mongodb-connection-failed', {
errorDetails: data
});
});
});
now at client side:
var socket = io();
socket.on('mongodb-connection-failed', () => {
console.log('you have been disconnected');
//do more whatever you want to.
});
This above example is using socket.io.
You can use any web socket library, see more here

Related

How to separate Socket.IO events from server.js?

I created Express, Node, React app.
Now, i want to integrate socket.io to the app.
I searched all over the internet and i found that all the socket.io events are in the initial server.js/app.js file.
But, i want to separate the socket.io events from the main file and then import it to the main file, just like routes/controllers files.
My code right now:
var app = require("express")();
var http = require("http").createServer(app);
var io = require("socket.io")(http);
const mongoose = require("mongoose");
const stocks = require("./routes/stockRoutes");
const bodyParser = require("body-parser");
const cors = require("cors");
const port = 5000;
app.use(stocks);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.set("socketio", io);
const uri =
"mongodb+srv://admin:admin1234#investockcluster0.jp2wh.mongodb.net/<stocks_data>?retryWrites=true&w=majority";
mongoose.connect(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("MongoDB database connection established successfully");
});
io.on("connection", (socket) => {
socket.emit("hello", "world");
console.log("New Connection");
});
http.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
I want that this code will be in file like "socketEvents.js" and then require it.
io.on("connection", (socket) => {
socket.emit("hello", "world");
console.log("New Connection");
});
Thanks a lot :)
Just put your socket.io code in another module and pass in the server in an initialization method:
// in sock.js
module.exports = function(server) {
const io = require("socket.io")(server);
io.on("connection", (socket) => {
socket.emit("hello", "world");
console.log("New Connection");
});
// put other things that use io here
}
Then, in your main file:
require('./sock.js')(http);
FYI, http is a crummy variable name for your server. You really ought to name it server.

Sending Object to group of users Node.js by using Socket.IO

I am using Node.js with Express.js and for realtime data I am using socket.io.
I am trying to create on booking app.
So when the user will request through REST api the server will store the information to mongoDB via mongoose and after that the same data will be send to other users.
I am using router for different paths. below is my server.js
var express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const routes = require('./routes/routes');
const port = process.env.PORT || 8080;
app.use(express.json());
app.use(cors())
app.use(express.urlencoded({ extended: false }));
app.set('socketio', io);
app.use(routes);
mongoose.Promise = global.Promise;
mongoose.connect(
'mongodb://localhost:27017/myapp',
{ useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, }
).then(() => {
console.log('db connected');
}).catch(err => {
console.log(err,"hello 1998");
});
server.listen(8080);
And below is my route
const { Router } = require('express');
var router = Router();
const { main } = require('../helper/db_main')
const { checkAuthentication } = require('../helper/auth')
router.use('/api/v1/services',main,checkAuthentication,require('../controllers/services'));
router.use('/api/v1/category',main,checkAuthentication,require('../controllers/category'));
router.use('/api/v1/socket',main,checkAuthentication,require('../controllers/socket'));
module.exports = router;
and below is the place where I am trying to send/emit data to specific user but it is not working on client side i.e not able to see emit message on front-end side.
const list_all_category = (req,res) => {
console.log("Hjdnckjsdck")
var io = req.app.get('socketio');
// global.io.to("notify_me").emit("message", "hello ftomr");
let result_data
category.list_all_category().then(save_res => {
if (save_res)
result_data = res.status(200).send(save_res)
else{
result = 'fail'
res.send()
}
})
console.log("Here is ninja",io.id)
io.on('connection', function(socket){
console.log(socket.id); // same respective alphanumeric id...
})
io.sockets.on('connect', function(socket) {
const sessionID = socket.id;
})
io.on('notify',function(){
console.log("Galgotia")
})
io.sockets.emit('chat_message', 'world');
}
make use of this
socket.broadcast.to('ID').emit( 'send msg', {somedata : somedata_server} );
you can het each socket id for a specific user by using ${Socket.id}
If you are emitting anything always send the socket.id of a user to the client and send them back to the server.

Node net.Socket emit data to all connected clients

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

Socket.io connects but does not receive message on the client

I implemented the server and client with socket.io and the server is working correctly, when some client connects it logs me in, but when I emit an event it does not arrive at the client, it follows the code to analyze:
And the console.log from socket object it says this:
connected:false,
disconnected:true
Server:
'use strict';
const chalk = require('chalk');
const _ = require('lodash');
const fs = require('fs');
let options = {
key: fs.readFileSync("privkey.pem"),
cert: fs.readFileSync("cert.pem")
};
const app = require('express')(options);
const https = require('https').Server(app);
const io = require('socket.io')(https,{origins:'*:*'});
const bodyParser = require('body-parser');
const multer = require('multer'); // v1.0.5
const upload = multer(); // for parsing multipart/form-data
const sockets = {};
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
https.listen(3002, function () {
console.log(chalk.yellow("Serviço rodando na porta 3002"));
});
io.on('connection', function (socket) {
console.log(chalk.green("Cliente Conectado"));
sockets[socket.id] = socket;
socket.on('disconnect', function () {
console.log(chalk.red("Cliente Disconectado"));
delete sockets[socket.id];
});
});
app.post('/atualizador', upload.array(), function (req, res) {
_.each(sockets,function(socket,idSocket){
console.log(idSocket);
socket.emit('posicao',req.body);
});
res.send('Atualizador ON');
});
Client:
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script>
localStorage.debug = '*';
const socket = io.connect('https://localhost:3002/atualizador',{'forceNew': true});
console.log(socket);
socket.on('connection', function (socket) {
console.log(socket);
socket.on('posicao', function (msg) {
console.log("Ok");
console.log(msg);
});
socket.on('teste', function (msg) {
console.log("Ok");
console.log(msg);
});
});
</script>

How to create a simple socket in node.js?

I'm trying to create a dummy socket for use in some of my tests
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.write("hello!");
Getting this error
Error: This socket is closed.
I've also tried creating the socket with
var s = new net.Socket({allowHalfOpen: true});
What am I doing wrong?
For reference, the complete test looks like this
it("should say hello on connect", function(done) {
var socket = new net.Socket();
var client = Client.createClient({socket: socket});
socket.on("data", function(data){
assert.equal("hello", data);
done();
});
client.connect();
// writes "hello" to the socket
});
I don't think the server is put into listening state. This what I use..
// server
require('net').createServer(function (socket) {
console.log("connected");
socket.on('data', function (data) {
console.log(data.toString());
});
})
.listen(8080);
// client
var s = require('net').Socket();
s.connect(8080);
s.write('Hello');
s.end();
Client only..
var s = require('net').Socket();
s.connect(80, 'google.com');
s.write('GET http://www.google.com/ HTTP/1.1\n\n');
s.on('data', function(d){
console.log(d.toString());
});
s.end();
Try this.
The production code app.js:
var net = require("net");
function createSocket(socket){
var s = socket || new net.Socket();
s.write("hello!");
}
exports.createSocket = createSocket;
The test code: test.js: (Mocha)
var sinon = require('sinon'),
assert = require('assert'),
net = require('net'),
prod_code=require('./app.js')
describe('Example Stubbing net.Socket', function () {
it("should say hello on connect", function (done) {
var socket = new net.Socket();
var stub = sinon.stub(socket, 'write', function (data, encoding, cb) {
console.log(data);
assert.equal("hello!", data);
done();
});
stub.on = socket.on;
prod_code.createSocket(socket);
});
});
We can create socket server using net npm module and listen from anywhere. after creating socket server we can check using telnet(client socket) to interact server.
server.js
'use strict';
const net = require('net');
const MongoClient= require('mongodb').MongoClient;
const PORT = 5000;
const ADDRESS = '127.0.0.1';
const url = 'mongodb://localhost:27017/gprs';
let server = net.createServer(onClientConnected);
server.listen(PORT, ADDRESS);
function onClientConnected(socket) {
console.log(`New client: ${socket.remoteAddress}:${socket.remotePort}`);
socket.destroy();
}
console.log(`Server started at: ${ADDRESS}:${PORT}`);
function onClientConnected(socket) {
let clientName = `${socket.remoteAddress}:${socket.remotePort}`;
console.log(`${clientName} connected.`);
socket.on('data', (data) => {
let m = data.toString().replace(/[\n\r]*$/, '');
var d = {msg:{info:m}};
insertData(d);
console.log(`${clientName} said: ${m}`);
socket.write(`We got your message (${m}). Thanks!\n`);
});
socket.on('end', () => {
console.log(`${clientName} disconnected.`);
});
}
function insertData(data){
console.log(data,'data');
MongoClient.connect(url, function(err, db){
console.log(data);
db.collection('gprs').save(data.msg , (err,result)=>{
if(err){
console.log("not inserted");
}else {
console.log("inserted");
}
});
});
}
using telnet:
$ telnet localhost 5000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
We got your message (hi). Thanks!
you need to connect your socket before you can write to it:
var PORT = 41443;
var net = require("net");
var s = new net.Socket();
s.on("data", function(data) {
console.log("data received:", data);
});
s.connect(PORT, function(){
s.write("hello!");
});
It will useful code for websocket
'use strict';
const express = require('express');
const { Server } = require('ws');
const bodyParser = require('body-parser');
const cors = require('cors');
const PORT = process.env.PORT || 5555;
const INDEX = '/public/index.html';
const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
router.get('/', function(req, res) {
res.sendFile(INDEX, { root: __dirname });
});
const server = express()
.use(router)
.use(bodyParser.json())
.use(cors)
.listen(PORT, () => {
console.log(`Listening on ${PORT}`)
});
const wss = new Server({ server });
wss.on('connection', (ws) => {
ws.on('message', message => {
var current = new Date();
console.log('Received '+ current.toLocaleString()+': '+ message);
wss.clients.forEach(function(client) {
client.send(message);
var getData = JSON.parse(message);
var newclip = getData.clipboard;
var newuser = getData.user;
console.log("User ID : "+ newuser);
console.log("\nUser clip : "+ newclip);
});
});
});

Resources