Angular-fullstack + socket.io
Blogs20142014-03-25
I want to integrate socket.io into Angular-fullstack. I found some documents are Vague, so use my way to do the easily implementation:
1. server side setting
First npm install socket.io, then use it in server.js:
// 1. install socket.io:
$ npm install socket.io --save
// 2. then in server.js, adding:
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
server.listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});2. client side setting
Similar as server-side, first bower install, then add it in angularâs âindex.htmlâ entry point.
$ bower install socket.io-client --save
// then in index.html, adding:
<script src='bower_components/socket.io-client/dist/socket.io.min.js'>
// An alternative way to add client-side's socket.io.js is to
// cp socket.io.js from node_modules/ to bower_components/, like this:
$ cd node_modules/socket.io/
$ find . -type f -name socket.io.js -exec mv {} ../../app/bower_components/ ;
//then:
<script src='bower_components/socket.io.js'>Any of them shoudl work. Basically the above 2 ways do the same thing: import socket.io.js client, then load into angularjs env.
After that, adding client emit/on in âindex.htmlâ to communicate with server side:
<script type="text/javascript" src="bower_components/socket.io-client/dist/socket.io.js">
<script>
var socket = io.connect('http://localhost:9000');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>Now start the service, monitor socket.ioâs behavors:
- $ grunt serve
- server-side: from command line, which is output of console.log()
- client-side: of cource the browserâs console
The messages transferred btw server/client should display properly.
