How to handle live messaging in Mean stack application? - node.js

I'm planning to develop a MEAN Stack application. After searching internet i'm not getting myself so clear on how to handle live messaging in my application which would just work like whatsapp/fb messenger or any other chat applications.
Initially i thought of using setTimeout function and make a REST call for latest data on some specified no.of seconds, but i don't know whether it's a feasible option.
Can anyone help me to understand what would be the best practice to update messages on both server and client sides?

You can use Socket.io. It is a websocket which allows you to communicate between browser and server. It's very easy to setup and start using.
You can install it with npm install --save socket.io (assuming you installed express already 'cause you want a MEAN app)
Then you can start with basics like this:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
You can find the documentations in here
Hope it helps!

Related

Express-Socket.IO App isn't working with my Azure WebApp

For educational purposes I try to deploy an Express Server that is using Socket.IO. The Server should be able to deliver a static HTML Site that was built with React, answer with a "Hello Azure!" message whenever I make a GET Rest Call to http://localhost:4000/api/azure and whenever a new client connects to the site, all the other clients get a message announcing the new client.
const path = require('path');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const router = require('./api/azure');
const PORT = process.env.PORT || 4000;
io.on('connection', () => {
console.log('A new user has connected!')
io.emit('broadcast', 'A new user has connected');
});
app.use(express.json());
app.use('/api/azure', router);
app.use(express.static(path.join(__dirname, 'build')));
app.use(express.static('public'));
app.use('/', (_, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
server.listen(PORT, () => {
console.log(`Listening to http://localhost:${PORT}`);
});
All this tasks are fulfilled without problems in localhost. The problem begins after this app is uploaded to one of my Azure WebApps.
Instead of delivering the message "Hello Azure!" when I call the https://mydomain.azurewebsites.net/api/azure it responses back with the HTML file.
The typical Socket.IO GET method for polling
https://mydomain.azurewebsites.net/socket.io/?EIO=4&transport=polling&t=SomeString
responses back with the HTML file, too.
Everything url extension that I give, gives me back the HTML file.
I barely know the basic stuff about WebApps. Maybe there is a configuration that I am forgetting? By the way I haven't done anything in the configuration except that I enabled the Websockets in the WebApp config.
This never happened before. The only difference is that right now I am using a free-tier just to test. Could it be that? If not, what am I doing wrong?
Thank you for your time!
To begin with, try turning the Web Socket config off as it applies to an IIS setting which tends to contradict with the Node.js websocket implementation.
If this doesn't help, try and force the transport layer to use Websockets and SSL.
io.configure(function() {
// Force websocket
io.set('transports', ['websocket']);
// Force SSL
io.set('match origin protocol', true);
});
Also, you cannot use arbitrary ports (port 4000 in your case) on services like App Service. Your app will be provided a port via process.env.PORT. So ensure that you are refering to the correct port from your log message. You should be able to see these in your log stream.
Also note, that Azure has launched a fully managed service called Web PubSub to power your apps with Web Sockets. The app service web socket implementation does not scale horizontally, this where Web PubSub will help you.
https://azure.microsoft.com/en-in/blog/easily-build-realtime-apps-with-websockets-and-azure-web-pubsub-now-in-preview/

How to test maximum connection Node JS websocket

I'm writing an Node JS socket App.
Case1: Base on this link
stackabuse.com/node-js-websocket-examples-with-socket-io/
I start the server on port 3000, go to browser, navigate to localhost:3000, i got index.html page and an connection to socket inside this file (you can find it in the link above).
This is my code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
console.log(current);
});
io.on('connection', function(socket){
//console.log('a user connected');
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.on('disconnect', function(){
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Case 2: I include socket.io.js file inside index.html file, then access it from browser (but not with port 3000 anymore) with apache like an normal site).
Code for Node server case 2
Then the script will create an websocket to localhost:3000 like this:
Client case 2
I only can test the maximum connect with case 1 (actually send alot GET request to get "index.html" page, not an real socket connection). I tested with thor, loadtest, benchmark, Artillery... and they're only work with case 1 :(
So, can I have any tool to test maximum connection in Websocket Node JS? I really need an usable tool to test websocket (not just HTTP GET).
Thansk for reading this question, and sorry for my English, by the way :(

Socket.io + Azure web sockets issue

I am working on a multiplayer chess game with NodeJS and socket.IO.
I have problem hosting it on Azure tho.. I tried many different approaches, a few mentioned:
Forcing the application to only use WebSockets by adding the code below:
io.configure(function() {
io.set('transports', ['websocket']);
});
Added <webSocket enabled="false"/> in web.config file..
Note: This disables the IIS WebSockets module, which includes its own implementation of WebSockets and conflicts with Node.js specific WebSocket modules such as Socket.IO. If this line is not present, or is set to true, this may be the reason that the WebSocket transport is not working for your application.
Matching origin protocol to ensure no SSL issues.
io.configure(function() {
io.set('match origin protocol', true);
});
I now started from scratch, since I thought my server-side part was corrupt, and tried Socket.io chat example instead.
I followed the steps.
Created a new web app on Azure.
Published my files through FileZilla FTP.
Enabled Web Sockets on Azure for my app (disabled by default).
STILL THE SAME ERROR! See picture below.
Anyone? I am unsure if it's a client-side or server-side issue. It seems like it's trying to XHR-poll instead of using web sockets..
Thanks in advance.
I got it working, thank you Chris Anderson-MSFT for your help.
The weird thing that occurred for me when deploying with FTP was that my node_modules folder differed with version(s) specified in my package.json.
I solved this by connecting my web app on Azure to a local Git repository and deploying the app through git. This connects my packages recursively and matches correct versions.
I also needed to enforce my client-side socket-io to use web sockets by specifying transport method:
var socket = io({transports:['websocket']});
And this is what my server-side file ended up looking like:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
app.use(express.static('public'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/default.html');
});
io.on('connection', function(socket) {
io.set('transports', ['websocket']);
console.log('new connection on socket.io');
socket.on('move', function(msg) {
socket.broadcast.emit('move', msg);
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});

support multiple protocols on single server

I have a working Express HTTP server as well as a working websocket server. I want to add the websockets application to my regular website which is run by the HTTP server, but I'm not sure I'm understanding the documentation. Can I have a server that accepts multiple protocols and how would I handle the routing in a situation like that? The npmjs documentation for socketio says:
In conjunction with Express
Starting with 3.0, express applications have become request handler functions that you pass to http or http Server instances. You need to pass the Server to socket.io, and not the express application function.
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(){ /* … */ });
server.listen(3000);
can I handle HTTP requests through app.HTTPverbHere() and websocket requests through io.on?
The socket.io documentation shows you the exact steps needed to make socket.io work with nodejs express on the same server.
So, YES, you can do this.
In fact, every webSocket connection starts with an HTTP request (which is then upgraded to the webSocket protocol) so you must have a web server running on the server that handles webSockets anyway.
socket.io simply hooks into one route on the express web server that is used to initiate all socket.io webSocket connections and handles things from there.
Here's one example taken directly from the socket.io doc:
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});

How to send a temporary chunk of html and js to a running app on node.js

I just got my first app up and running on Node.js. As of now, it is simply serving up a static file. But I have a few ideas that will be implemented down the road so I'm going ahead and getting Node setup so I'll be ready for it when that time comes.
// get modules
var express = require('express');
var fs = require('fs');
// create app instance
var app = express();
// static files middleware
app.use("/assets", express.static(__dirname + '/assets'));
// main route
app.get('/', function(req, res) {
var html = fs.readFileSync('assets/views/main.html', 'utf8');
res.send(html);
});
// make web server listen on specific port
app.listen(8080);
NOTE: I realize I don't need Express to serve one route, but I figured what's the harm in getting a head start on that as well?! :)
The first idea i had is to make a way to let all users currently using the app that there has been an update and that they must refresh their browser. There is no need to save the current state of the app as it is pretty basic.
So, if I am a user, I'm using the app and boom, I get a pretty little modal-window-alert-notification thingy letting me know that I need to refresh.
Also, if some user loads the app AFTER I have sent the alert, that user should not see the alert at all (because they should already be seeing the new changes).
I have done some googling on the subject and I'm just not satisfied with the examples i found. I do not think I want to have to update a notifications.xml file (which node.js would be watching) to push a new notification.
One solution I can think of would be to make a command that can be executed from the command line that will (somehow) send a new notification to the app. Perhaps using something like Grunt.js (I'm not sure if it would be a good fit for this as I've never used it). Basically, once the notification has been sent, all traces of it should disappear. That's why I think a command line approach would be good.
Here's my question: How (generally speaking) should I implement something like this? I am a Node.js newbie but I am pretty comfortable with javascript and the command line.
Please feel free to offer up any alternative solution you think would be better for me (other than a command line approach), or any tools that you think could help me.
Thanks!
If you want to push updates to a web client, one way is to use something like Socket.io. This creates a two-way pipe between client and server that you can use to asynchronously push updates through.
Sample server:
var app = require('express').createServer()
, io = require('socket.io').listen(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Sample client:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
alert('New news has come in! Please refresh your page!');
socket.emit('my other event', { my: 'data' });
});
</script>
The other option is to poll from the client using Javascript to actively look for updates. You would need to keep some state on the server for each client that would determine if that client required an update. The client would then make a get request on some timer interval (once a second, for example) to a secondary route and the server would reply with 'Yes, you need an update' or 'No, you don't need an update'. If yes, the client Javascript would then pop up your modal box and tell the user to refresh.

Resources