#ConFoo
@joel__lord
Real-time live slides, see my Twitter account
@joel__lord
@joel__lord
#ConFoo
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.
#ConFoo
@joel__lord
#ConFoo
@joel__lord
#ConFoo
@joel__lord
#ConFoo
@joel__lord
#ConFoo
@joel__lord
#ConFoo
@joel__lord
var connection = new WebSocket('ws://somedomain/path/')
#ConFoo
@joel__lord
connection.onopen = function(e) {
console.log("Connected");
};
connection.onmessage = function(e) {
console.log( "Received: " + e.data);
};
connection.onclose = function(e) {
console.log("Connection closed");
};
#ConFoo
@joel__lord
//Strings
connection.send('this is a string');
//Array Buffers
var image = aCanvas.getImageData(0, 0, 640, 480);
var binary = new Uint8Array(image.data.length);
for (var i = 0; i < image.data.length; i++) {
binary[i] = image.data[i];
}
connection.send(binary.buffer);
//Blobs
var myFile = document.querySelector('input[type="file"]').files[0];
connection.send(myFile);
//JSON objects ?
var jsonObject = JSON.stringify({"data": "value"});
connection.sent(jsonObject);
#ConFoo
@joel__lord
Server and client-side implementation
Falls back to long polling when necessary (IE 9)
Adds features like heartbeats, timeouts, and disconnection support not provided in WebSocket API
Easy stuff !
#ConFoo
@joel__lord
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>
#ConFoo
@joel__lord
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);
});
});
#ConFoo
@joel__lord
#ConFoo
@joel__lord
@joel__lord
http://github.com/joellord
me@joel-lord.com
#ConFoo
@joel__lord