Just to say that the latest builds of Espruino now support WebSocket server in JS. Not only that, but mixed WebSocket and HTTP server!.
For instance:
page = '<html><body><script>var ws;setTimeout(function(){';
page += 'ws = new WebSocket("ws://localhost:8000/socketserver", "protocolOne");';
page += 'ws.onmessage = function (event) { console.log("MSG:"+event.data); };';
page += 'setTimeout(function() { ws.send("Hello to Espruino!"); }, 1000);';
page += '},1000);</script></body></html>';
function onPageRequest(req, res) {
if (req.headers.Connection=="Upgrade") {
var key = req.headers["Sec-WebSocket-Key"];
var accept = btoa(E.toString(require("crypto").SHA1(key+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")));
res.writeHead(101, {
'Upgrade': 'websocket',
'Connection': 'Upgrade',
'Sec-WebSocket-Accept': accept,
'Sec-WebSocket-Protocol': req.headers["Sec-WebSocket-Protocol"]
});
var ws = require("ws")(undefined,{
serverRequest : req,
serverResponse : res
});
ws.on('message',function(msg) { print("MSG:"+msg); });
ws.send("Hello from Espruino!");
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(page);
}
}
require('http').createServer(onPageRequest).listen(8000);
I had to tweak the WebSocket library a bit, but it hopefully at some point the code above can mostly be rolled into the library and you'll be able to do something like:
function onPageRequest(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(page);
}
require('ws').createServer(onPageRequest).listen(8000);
Espruino is a JavaScript interpreter for low-power Microcontrollers. This site is both a support community for Espruino and a place to share what you are working on.
Hi,
Just to say that the latest builds of Espruino now support WebSocket server in JS. Not only that, but mixed WebSocket and HTTP server!.
For instance:
I had to tweak the WebSocket library a bit, but it hopefully at some point the code above can mostly be rolled into the library and you'll be able to do something like: