Express and socket.io chat? - javascript

I can set up the chat no problem, but my question is how do I get the chat to work on the default port:80 where my main site is?
First thing that comes to mind is iframing it?
Here is my server.js code, one thing to note I don't really like jade so I am going to convert that into plain HTML. Also for the chat to work it has to be on any port other than :80 so I am not quite sure how to get it to work on that main port, other than iframing?
So my question is obviously what are my options in getting the express server to work on the main port?
// Start server
var express = require("express");
var app = express();
var port = 3700;
// Directory
app.use(express.static(__dirname + '/chat'));
// Socket.io integration
var io = require('socket.io').listen(app.listen(port));
// Render content
app.set('views', __dirname + '/tpl');
app.set('view engine', "jade");
app.engine('jade', require('jade').__express);
app.get("/", function(req, res){
res.render("page");
});
// Recieve msg and send
io.sockets.on('connection', function (socket) {
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});

You dont realy need node-expres-jade on the port 80 for these aproach.
Node can just run the socket server (alone). Forget express/jade here.
And apache or nginx can handle all de client-side files (html, js , css ...).
add the var socket = io.connect('httt://yoururl:port'); on any html an it should work.

Related

Node.js multiple apps

I have a platform running with Apache + PHP which I distribute to several people through subdomains, Ex: platform.subdomain1.com, platform.subdomain2.com,etc..
. And I would like one of the features of this platform to be Video streaming and i chose to do this with Node.js + socket.io. I don't have much Node experience but I managed to make streaming itself work. I basically have a directory called stream with app.js, index.html and two html files: one to stream the video and one to view.
My problem:
I would like to merge the two so that I can link to these streaming and viewing pages so that each user with their subdomain has their own streaming.
I wonder if there is any way to do it and what it would be.
I could create a directory with the all node streaming files inside each subdomain and create a new instance for each one, like this:
var app = new express();
const http = require("http").Server(app)
http.listen('platform.subdomain1.com',3000);
So that I could link my platform to the address: platform.subdomain1.com/stream:3000
but I'm not sure if it is right to do this or if there is another way to do it. If anyone can help me thank you very much!
My App.js
var express = require("express");
var app = new express();
const http = require("http").Server(app)
var io = require("socket.io")(http);
app.use(express.static(__dirname + "/public"));
app.get('/', function(req,res){
res.redirect('index.html');
});
io.on('connection', function(socket){
socket.on('stream', function(image){
socket.broadcast.emit('stream', image);
});
});
http.listen(3000);
yes, this is the right way to work with socket.io and express together
create express server
bind express server to socket.io
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
// WARNING: app.listen(80) will NOT work here!
app.get('/ping', function (req, res) {
res.send("pong")
});
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);
});
});
Advantage with express:
You will have support for ping/pong or health check in case of AWS load balancer health check or any platform that route request base on target health as socket.io does not support health check in AWS ALB.
you check official documentation suggested by socket.io.
socket.io-Using-with-Express

Sending Status Codes in NodeJS when serving static content

I am building a simple nodejs server to serve static content for a webpage. I want to send status codes back but when I try to create a function for the app.use() the content is not served.
var express = require('express')
var app = express();
app.listen(3000, function() {
console.log("We are now listening on Port:3000")
app.use(express.static('public'));
app.use('*', express.static('public/404.html'));
});
The content is served when I run this, but I cannot get the status codes as I need. Any help is appreciated.
I don't know exactly what you want. This is my suggest solution:
var express = require('express')
var app = express();
app.listen(3000, function() {
console.log("We are now listening on Port:3000")
app.use(express.static('public'));
app.use('*', function(req, res) {
// change your status code here
res.status(404).sendFile(__dirname + "/public/404.html");
});
});

How can I serve my web app with Node/Express?

I'm probably going to ask a huge noob question, one of the worst I've ever had asked here, but I'm lost as hell with Node/Express. I've only used Apache servers (typical WAMP/XAMP for testing purposes), so I have absolutely no idea on what I have to do to serve my web app.
My folder tree is the following:
www
nodeserver.js
(more things)
Liteconomy (my web app)
js
css
plugins
templates
index.html
sublime_project
Pretty typical, huh? Well, I've been searching how to serve this app with a simple access like localhost:8080/Liteconomy, or localhost:8080/Liteconomy.html. After that, my angular routing would do the rest, but I just can't serve the app.
I've got this written in nodeserver.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
When I execute it and access to localhost:8080, I get the "Hello world", but when I go to localhost:8080/Liteconomy, I get the following plain text: "Liteconomy/index.html". If I try to access to the index resource directly, I get a "Cannot GET /Liteconomy/index.html" error.
I also tried using the static thingy, but didn't work either.
What am I doing wrong here? I guess I'm just missing something very important.
Do the following, it will resolve your issue.
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// uncomment following if you want to access your app from /liteconomy
//app.use('/liteconomy', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
//This will enable you to access it form '/'
app.use('/', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
// Rest of the stuff
Then if you will visit your URL that you set and port, you'll be able to access.
Using express.static is recommended way of serving static content.
Hope it helps!
You get a plain text answer because you actually ask to do it with the :
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
If you want to send a simple html file like your index.html file, you should use the "sendfile " function :
app.get('/Liteconomy', function (req, res) {
res.sendfile(__dirname + '/Liteconomy/index.html');
});
"__dirname" represents your root directory path and then you simply put your file path.
Hope that helps !
PS : by default express come with jade and ejs template support instead of just using html. I would advise you to take a look at one of them, it can be a great help to construct your application web pages.

Configuring 'simplest' node.js + socket.IO + Express server

Realized after setting up a simple node.js socket.IO server that it isn't sufficient to handle even the simplest webpages containing script tags.
So I investigating express which is a simple web framework for node.js.
After looking thru the express documentation http://expressjs.com/guide.html
I was still confused as to how I simply combine express with socket.IO on a node.js server.
Couple hours of googling later I came across this tutorial
https://www.digitalocean.com/community/articles/how-to-install-express-a-node-js-framework-and-set-up-socket-io-on-a-vps
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server); // this tells socket.io to use our express server
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
console.log("Express server listening on port 3000");
io.sockets.on('connection', function (socket) {
console.log('A new user connected!');
socket.emit('info', { msg: 'The world is round, there is no up or down.' });
});
My question is, would anyone reading this configure their server differently?
I don't need anything special, no session handling etc, just the ability to serve html pages containing links to external CSS and javascript files.
Remove the first app.configure wrapper but leave it's contents. It is useless in general, but especially if you don't pass an argument to it.
Remove methodOverride and bodyParser as you aren't using them
Thanks for all the replies. Finally have something that works and am posting so someone else may benefit. My first attempt(above) was obviously NOT the simplest solution:)
//npm install express
//npm install socket.io
var express = require('express');
var server = express.createServer();
server
.use( server.router )
.use( express.static(__dirname+'/public') )
.get('/api', function(req, res) {
res.write('API');
});
server=server.listen(3000);
var io = require('socket.io');
var socket = io.listen(server);
socket.on('connection', function (client){
// new client is here!
});

Node.JS - Simple Socket.IO example not working. Getting debug - served static content /socket.io.js (Mac OSX/Localhost)

I just began with node.js a few days ago and I'm know trying to use socket.io module. But it is not working as I was expecting. The example I am trying to reproduce is this one :
http://robdodson.me/blog/2012/06/04/deploying-your-first-node-dot-js-and-socket-dot-io-app-to-heroku/
I know that the version of Express they are using is outdated so I updated my code to fit with the new versions of the modules they are using.
The problem I have is that my client doesn't get what my server is emitting, here is my server-side code :
var express = require('express'),
http = require('http'),
app = express(),
port = 8080, // Use 8079 for dev mode
server = http.createServer(app).listen(process.env.PORT || port, function(){
console.log('Express server listening on port %d in %s mode', server.address().port, app.settings.env);
}),
io = require('socket.io').listen(server),
routes = require('./routes');
// Configuration
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function() {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
// Heroku won't actually allow us to use WebSockets
// so we have to setup polling instead.
// https://devcenter.heroku.com/articles/using-socket-io-with-node-js-on-heroku
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
// Routes
app.get('/', routes.index);
var status = "All is well.";
io.sockets.on('connection', function (socket) {
io.sockets.emit('status', { status: status }); // note the use of io.sockets to emit but socket.on to listen
socket.on('reset', function (data) {
status = "War is imminent!";
io.sockets.emit('status', { status: status });
});
});
And here is client-side :
<script src="http://localhost:8080/socket.io/socket.io.js">
var socket = io.connect(document.location.href);
</script>
<div id="status"></div>
<button id="reset">Reset!</button>
So if I understood well, what I should get is "All is well" on the first time in the status div, and "War is imminent !" if I click reset.
But all I get is nothing.
I tried those answers but I can't see any differences between the solution code and mine, or sometimes it's just outdated :
1. Node.js + socket.io: app on server not working correctly
2. NodeJS - Socket.IO Setup: served static content no handshake (Ubuntu on Rackspace Cloud Server)
I tried all of the solutions that were given in the other subjects but it definitely won't work for me.
Every modules are correctly installed. I followed the steps given in the tutorial I followed at first.
If anyone has any idea of what is going on or if anyone experienced the same issue you are welcome.
Thanks.
The reason your client isn't doing anything is because you aren't telling it to do anything. You need to assign handlers for it to do something. So, to fix this, you'd need to tell the reset button to use socket.emit() when being clicked, and you'd also need to assign a handler for the status event in order to change the contents of the div.
<script type="text/javascript" src="http://localhost:8080/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect(document.location.href);
</script>
<div id="status"></div>
<button id="reset" onclick="socket.emit('reset')">Reset!</button>
<script type="text/javascript">
socket.on('status', function(data) {
document.getElementById('status').innerHTML = data.status;
});
</script>

Categories