Websockets 101: using socket.io
About me
@joel__lord
http://github.com/joellord
jlord@macadamian.com
What's that ?
-
WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocketAPI in Web IDL is being standardized by the W3C.
Browser support
- Firefox 11+
- Chrome 11+
- Safari 6+
- Opera 12.10
- Android Browser 4.4
- Internet Explorer 10+
Pros
- Bi-directional data transfers
- Fast
- Low bandwith
Cons
...
Real world cases
- Real time synchronization of data amongst a group of users (trello.com)
- Live feeds (twitter stream)
- Long server processes and providing ETAs to users
Websocket libraries
- Ratchet (php)
- Jetty (Java)
- socket.io (node.js)
Using socket.io
- Easy stuff !
Server implementation
//Express server setup
var express = require("express");
var app = express();
var server = require("http").createServer(app);
var port = 8888;
server.listen(port, function () {
console.log("Server started on port " + port);
});
app.use(express.static(__dirname + "/../"));
//Socket setup
var io = require("socket.io")(server);
io.on("connection", function (socket) {
socket.on("messageFromClient", function (data) {
socket.broadcast("messageFromServer", data);
});
});
Client implementation
<body>
<input type="text" id="textField" />
<button type="button" id="sendMsg">Send</button>
<textarea id="msgBox"></textarea>
</body>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io();
document.getElementById("sendMsg").onclick = function() {
socket.emit("messageFromClient", {text: document.getElementById("textField").value});
};
socket.on("messageFromServer", function(data) {
document.getElementById("msgBox").value += data.text;
});
</script>
Code time !
Questions ?
@joel__lord
http://github.com/joellord
jlord@macadamian.com