How to make works socket.io/nodejs on c9.io

I have discovered this amazing site http://c9.io it allows you to code online and deploy your projet on another server.
You can get your source from a github if you want too.

I wanted to make a little concept and looked at c9.io documentation here:
https://c9.io/site/blog/2013/05/native-websockets-support/

But their code doesn’t work so I have done my own example based on socket.io official documentation http://socket.io/#how-to-use

Don’t forget to install choose nodejs project when you create one on c9.io and after use « $ npm install socket.io » to install socket.io

First create a file called server.js and put this code on:

var app = require(‘http’).createServer(handler)
, io = require(‘socket.io’).listen(app)
, fs = require(‘fs’)

app.listen(8080);

function handler (req, res) {
fs.readFile(__dirname + ‘/index.html’,
function (err, data) {
if (err) {
res.writeHead(500);
return res.end(‘Error loading index.html’);
}

res.writeHead(200);
res.end(data);
});
}

io.sockets.on(‘connection’, function (socket) {
socket.emit(‘news’, { hello: ‘world’ });
socket.on(‘my other event’, function (data) {
console.log(data);
});
});

———————- > to launch the file type in your console node server.js

you should have:
bash-4.1$ node server.js
info – socket.io started

And now create a file called index.html and put this code on: (same as c9 example)

var socket = io.connect(‘http://appName.userName.c9.io:8080′);
socket.on(‘news’, function (data) {
console.log(data);
socket.emit(‘my other event’, { my: ‘data’ });
});

———————> launch your url (ex: https://appName-userName.c9.io/)

and you should see in your console debug – served static content /socket.io.js

Hope it helps.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *


Time limit is exhausted. Please reload CAPTCHA.