Using Socket.io in Express.js Project - node.js

I'm making some single page web application with Node.js, Express and Socket.io. I want to display how works are going to browser. In IDE, There is console, so I can check program process in console window. Like, I want to show these process to browser. All I want to is just 'emit'.
When I use socket.io in app.js file, there is no problem. but this is limited for me. I want to display many sentences in realtime as running. How can I use socket.io in not only app.js but controller.js? I red Use socket.io in controllers this article, but I can't understand. Please help me with a simple solution.
app.js
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
module.exports.io = io;
...
controller.js
var io = require('./app').io;
// some task
console.log('Task is done!'); // it would be seen in console window
io.sockets.emit('Task is done!'); // Also I want to display it to broswer
Result (error)
TypeError: Cannot read property 'sockets' of undefined
Edit 2---
Follwoing Ashley B's comments, I coded like this.
controller.js
module.exports.respond = function(socket_io) {
socket_io.emit('news', 'This is message from controller');
};
app.js
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var controller = require('./controller');
io.sockets.on('connection', controller.respond );
It works well, But what I wonder is... When I want to several socket_emit, What Should I do? Should I call everytime? If you don't understand. see below :
//first task is done
module.exports.respond = function(socket_io) {
socket_io.emit('news', 'First task is done!');
};
//second task is done
module.exports.respond = function(socket_io) {
socket_io.emit('news', 'Second task is done!');
};
//third task is done
module.exports.respond = function(socket_io) {
socket_io.emit('news', 'Third task is done!');
};
But It is wrong way, right? only last api is implemented in app.js. There are a lot of console.log in my controller, I want to convert it to socket.emit How can I do this?

I have worked on this using socket.io and nodejs events. The idea is to handle the emission of the socket only from the app.js, and emit nodejs events from controllers, which will be captured in app.js and then issued by the socket.
app.js
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
const events = require('events');
io.on('connection', function(socket) {
console.log("Someone has connected");
var eventEmitter = new events.EventEmitter();
eventEmitter.on("newEvent", (msg) => { // occurs when an event is thrown
socket.emit("news", msg);
});
exports.emitter = eventEmitter; // to use the same instance
});
myController.js
const app = require('../app');
.....
if (app.emitter) // Checking that the event is being received, it is only received if there is someone connected to the socket
app.emitter.emit("newEvent", "First task is done!");
.....
if (app.emitter)
app.emitter.emit("newEvent", "Second task is done!");

Related

How to prevent people from connecting to any id with sockeIO?

I just set up SocketIO in my PHP project. I am completly new to websockets at all so bear with me.
I am defining the socketIO variable globally
let socketIO = io("http://localhost:3000");
When people are logging in to my application, they are connected to it with their ID comming from the database. The login script just gives back true which redirects the user in very simplified terms:
// get component
$.get(url, data, (data) => {
if (data.status) {
// connect with Node JS server
socketIO.emit("connected", data.user_id);
// redirect
load_new_page("/users/" + data.user_id);
}
});
My concern here now is that people could just go and change the data.user_id to anything they want and receive what ever the chosen id would receive.
My server.js:
// initialize express server
var express = require("express");
var app = express();
// create http server from express instance
var http = require("http").createServer(app);
// include socket IO
var socketIO = require("socket.io")(http, {
cors: {
origin: ["http://localhost"],
},
});
// start the HTTP server at port 3000
http.listen(process.env.PORT || 3000, function () {
console.log("Server started running...");
// an array to save all connected users IDs
var users = [];
// called when the io() is called from client
socketIO.on("connection", function (socket) {
// called manually from client to connect the user with server
socket.on("connected", function (id) {
users[id] = socket.id;
});
});
});
How can I prevent something like this?

Implement socket.io in node.js application controller

good afternoon. I am new to programming sockets in node.js and I need to implement socket.io in a controller of my application. The architecture I have is the following:
The file that starts the server is index.js
const express = require('express');
const app = express();
const port = 3000;
const socketRouter = require('./routes/socket')
app.use(express.json());
//Route
app.use('/socket', socketRouter);
app.listen(port, () => {
console.log(`Server connection on http://127.0.0.1:${port}`); // Server Connnected
});
The file where I define the routes is socket.js
const { Router } = require('express');
const { showData } = require('../controllers/socket');
const router = Router();
router.post('/send-notification', showData);
module.exports = router;
And my controller is:
const { response } = require('express');
const showData = (req, res = response) => {
const notify = { data: req.body };
//socket.emit('notification', notify); // Updates Live Notification
res.send(notify);
}
module.exports={
showData
}
I need to implement socket.io in this controller to be able to emit from it but I can't get it to work. Could you tell me how to do it?
Thanks a lot
CLARIFICATION: if I implement socket.io in the main file it works, but I want to have some order and separate things. This is how it works:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.post('/send-notification', (req, res) => {
const notify = { data: req.body };
socket.emit('notification', notify); // Updates Live Notification
res.send(notify);
});
const server = app.listen(port, () => {
console.log(`Server connection on http://127.0.0.1:${port}`); // Server Connnected
});
const socket = require('socket.io')(server);
socket.on('connection', socket => {
console.log('Socket: client connected');
});
Move your socket.io code to its own module where you can export a method that shares the socket.io server instance:
// local socketio.js module
const socketio = require('socket.io');
let io;
modules.exports = {
init: function(server) {
io = socketio(server);
return io;
},
getIO: function() {
if (!io) {
throw new Error("Can't get io instance before calling .init()");
}
return io;
}
}
Then, initialize the socketio.js module in your main app file:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
const server = app.listen(port, () => {
console.log(`Server connection on http://127.0.0.1:${port}`); // Server Connnected
});
// initialize your local socket.io module
const sio = require('./socketio.js');
sio.init(server);
// now load socket.io dependent routes
// only after .init() has been called on socket.io module
const socketRouter = require('./routes/socket')
app.use('/socket', socketRouter);
Then, anywhere you want to access the socket.io server instance, you can
require("./socketio.js") and use the .getIO() method to get the socket.io instance:
// use correct path to socketio.js depending upon where this module
// is located in the file system
const io = require("../../socketio.js").getIO();
// some Express route in a controller
const showData = (req, res) => {
const notify = { data: req.body };
// send notification to all connected clients
io.emit('notification', notify);
res.send(notify);
};
module.exports= {
showData
};
Note: A typical socket.io usage convention on the server is to use io as the server instance and socket as an individual client connection socket instance. Please don't try to use socket for both. This makes it clear that io.emit(...) is attempting to send to all connected clients and socket.emit() is attempting to send to a single connected client.
Also note that if your route is triggered by a form post where the browser itself sends the form post, then that particular client will not receive the results of io.emit(...) done from that form post route because that browser will be in the process of loading a new web page based on the response of the form post and will be destroying its current socket.io connection. If the form post is done entirely via Javascript using an Ajax call, then that webpage will stay active and will receive the results of the io.emit(...).
You can use the same socket and app (if you need to expose APIs as well) in other files if you want to separate socket messages and REST endpoints by functionality or however you choose to organize it. Here's an example of how this can be done:
Create a new file, let's say controller1.js:
function initialize(socket, app) {
socket.on('some-socket-message', socket => {
// Whatever you want to do
});
app.get('/some-endpoint', (req, res) => {
// whatever you want to do
});
}
module.exports = {initialize}
And then add the following to your controller.js
const controller1 = require('path/to/controller1');
...
// At some point after socket and app have been defined
controller1.initalize(socket, app);
This will be the bases of separating your controller however you want, while still using the same socket connection and API port in all of your controllers. You can also refactor the initialize method into different methods, but that would be at your own discretion and how you want to name functions, etc. It also does not need to be called initalize, that was just my name of preference.

Socket.js inside controllers in server(Node.js)

I am on the process of building a chat application with nodejs, reactjs mongo and socket.io.My chat app consists of both one to one and group chats.I have built a schema for group chat and i am inserting group names along with its members and their chats in the table.Since im a beginner towards socket.io, I dont know where to put the socket logic that needs to be fired after the db post operation.Can some one suggest any examples for me?
Update your code accordingly:
=> server.js file
// Declare socket.io
const io = require('socket.io')(server);
// Add middleware to set socket.io in
app.use((req, res, next)=>{ res.locals['socketio'] = io; next(); });
=> In your controller file
// Get the value of socket.io
module.exports = your_function_name = (req, res) => {
const io = res.locals['socketio']
// Use io when you need.
});
Hope this solves your query.
You can separate you socket related code by following way :
==>app.js
var express = require('express');
var socket = require('./socketServer');
var app = express();
var server = app.listen((config.node_port || 3000), function () {
console.log('Listening on port ' + (config.node_port || 3000) + '...');
});
socket.socketStartUp(server);
module.exports = app;
==>socketServer.js
var io = require('socket.io')();
var socketFunction = {}
socketFunction.socketStartUp = function (server) {
io.attach(server);
io.on('connection', function (socket) {
console.log("New user is connected with socket:", socket.id);
})
}
module.exports = socketFunction;
You can also check node API startup code with socket functionality in below link:
Node API Start up
Hope this answer is helpful to you

ExpressJs - SocketIo.client - emit not working

I am trying to connect to the crypto compare's api websockets to get the up to date prices for crypto currencies. I am using expressjs for my server and socketio to connect to crypto compare.
However after logging connected nothing else seems to happen.
This is my first time trying to play with sockets so I am a little lost as to why the io.emit function is not triggering anything.
Also there seems to be an issue in the callback of connect as socket is undefined!
Why does emit not seem to be doing anything?
My app.js file:
const express = require('express');
const app = express();
const clientIo = require('./lib/client-socket/crytpto-compare-socket');
clientIo.connect();
app.disable('x-powered-by');
module.exports = app;
Crypto-compare-socket.js
const io = require('socket.io-client');
const configs = require('./../config/configs');
const crytpCompareConfigs = configs.get('CRYPTO_COMPARE_API');
const cryptoCompareEndpoint = crytpCompareConfigs.ENDPOINT;
const cryptoCompareSocket = io(cryptoCompareEndpoint, {reconnect: true});
cryptoCompareSocket.on('connect', (socket) => { // socket here is undefined
console.log('Connected');
cryptoCompareSocket.emit('SubAdd', { subs: crytpCompareConfigs['LIST_OF_ITEMS']});
});
cryptoCompareSocket.on('SubAdd', (from, msg) => {
console.log('Hello');
console.log(from);
console.log('*******');
console.log(msg);
});
module.exports = cryptoCompareSocket;
The code you are using is client side code. This code does not return a socket in the callback because the client already knows the socket its connected with.
You are subscribing to a socket service, but you do not have any code that responds to data sent from that service.
When crypto compare returns data it sends the "m" event. So you need to respond to "m".
An example
cryptoCompareSocket.on("m", function(message) {
console.log(message);
});

NodeJS: Fetching Data whenever the server starts

I'm new to Node and async programming. I'm building a website in which I have to fetch some data from external websites and show it to client(AngularJS Client).
What I want to do is that whenever my server starts, it should fetch data from the external websites and place it in DB.
I have following code in my server.js file:
var express = require('express'),
app = express(),
abc = require('./server/controllers/abc');
app.listen(3000, function () {
console.log('I\'m listening...');
});
app.on('listening', function(){
abc.visitPages;
});
and following snippet in abc.js:
module.exports.visitPages = function () {
console.log('Going to visitPages');
}
my server works fine but it does not go to the visitPages() function in abc.js any help in this regard would be very kind.
thanks in advance.
You need to make sure you're actually running the function. Unlike some other languages, you must provide the parentheses to signify that the function should be invoked in javascript.
Use abc.visitPages() inside your listen callback.
Also, I'm not sure app.on('listener') will ever fire. Looks like express doesn't support it. I would move the method call into your app.listen() callback instead.
app.listen(3000, function () {
console.log('I\'m listening...');
abc.visitPages();
});
You can directly call you function .
var express = require('express'),
app = express(),
abc = require('./server/controllers/abc');
abc.visitPages();
app.listen(3000, function () {
console.log('I\'m listening...');
call_my_function();
});
Here's what you want, note that there is no event called listening, you have to emit it
var express = require('express'),
app = express(),
abc = require('./server/controllers/abc');
app.listen(3000, function() {
console.log('I\'m listening...');
app.emit('listening'); // <-- just emit this event
});
app.on('listening', function() {
abc.visitPages(); // <-- call function
});
//alternate
app.on('listening', abc.visitPages);

Resources