Julián Duque
Developer and Educator
http://about.me/julianduque - @julian_duque
$ npm install ws
$ cat > server.js
var wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function (ws) {
ws.send('Hello from WS Server');
ws.on('message', function (msg) {
console.log('Received: ' + msg);
if (msg == "hello") {
ws.send("Hello from server!");
}
});
});
$ node server.js
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = function () { console.log('Connected') };
ws.onerror = function (err) { console.log(err) };
ws.onmessage = function (e) { console.log(e.data); };
$ npm install socket.io
$ cat > server.js var socketio = require('socket.io'); var http = require('http'); var fs = require('fs'); var server = http.createServer(function (req, res) { res.writeHead(200, { 'Content-type': 'text/html' }); fs.createReadStream('./index.html').pipe(res); }); server.listen(8080); var io = socketio.listen(server); io.on('connection', function (socket) { socket.emit('hello', 'from server!'); socket.on('hello', function (msg) { console.log('Received: %s', msg); socket.emit('world'); }); });
$ node server.js
<p>Let's test Socket.io</p>
<script src="/socket.io/socket.io.js"></script>
<script> var socket = io.connect('http://localhost:8080'); socket.emit('hello', 'Hello from client!'); socket.on('hello', function (msg) { console.log('Received ' + msg); }); </script>
Cross domain Connections
var Primus = require('primus'),
http = require('http'),
fs = require('fs');
var server = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream('./index.html').pipe(res);
});
var app = new Primus(server, { transformer: 'engine.io' });
app.use('emitter', 'primus-emitter')
server.listen(8080);
app.on('connection', function (socket) {
socket.emit('hello', 'from server');
socket.on('hello', function (msg) {
console.log('Received: %s', msg);
});
});
<p>Let's test Primus!</p>
<script src="/primus/primus.js"></script>
<script>
var socket = Primus.connect('http://localhost:8080')
socket.on('hello', function (data) {
console.log('Received: ' + data);
socket.emit('hello', 'from client!');
});
</script>
By Julián Duque