Содержание по основным темам журнала:
Внезапно облачное будущее настало. Mac стал не очень нужным файловым хранилищем.
Ну все, теперь можно пересесть за Chromebook. Счастливо оставаться!
donclick.it-интерфейса мог бы быть пригодным для ввода-вывода в форме очков или, даже лучше, контактных линз, показывающих Web-страницу и использующих положение глаза как курсор.А вот этого я уже в других языках программирования как-то не видал. Эдакая «лиспо-лямбда» получается:
alexo@codedot:~$ wscat -c ws://localhost:8080/ connected (press CTRL+C to quit) < (function () { socket.say = function(data) { data = JSON.stringify(data); this.send(data); }; })(undefined) < (function () { socket.say("Hello World!"); })(undefined) > "Hello World!" < (function (data) { window.alert(data); })("Hello World!") disconnected alexo@codedot:~$
Кстати, wscat вчера починили.
Опубликовал свой первый пакет на свалке Node.js. Теперь запустить пример с «Hello World!», который будет доступен по локальному адресу, можно следующим образом:
alexo@codedot:/tmp$ npm install uniweb npm http GET https://registry.npmjs.org/uniweb npm http 200 https://registry.npmjs.org/uniweb npm http GET https://registry.npmjs.org/ws npm http 304 https://registry.npmjs.org/ws > ws@0.4.13 preinstall /private/tmp/node_modules/uniweb/node_modules/ws > make node-waf configure build Checking for program g++ or c++ : /usr/bin/g++ Checking for program cpp : /usr/bin/cpp Checking for program ar : /usr/bin/ar Checking for program ranlib : /usr/bin/ranlib Checking for g++ : ok Checking for node path : ok /usr/local/lib/node_modules Checking for node prefix : ok /usr/local 'configure' finished successfully (0.183s) Waf: Entering directory `/private/tmp/node_modules/uniweb/node_modules/ws/build' [1/4] cxx: src/validation.cc -> build/Release/src/validation_1.o [2/4] cxx: src/bufferutil.cc -> build/Release/src/bufferutil_2.o [3/4] cxx_link: build/Release/src/validation_1.o -> build/Release/validation.node [4/4] cxx_link: build/Release/src/bufferutil_2.o -> build/Release/bufferutil.node Waf: Leaving directory `/private/tmp/node_modules/uniweb/node_modules/ws/build' 'build' finished successfully (1.050s) npm http GET https://registry.npmjs.org/commander npm http GET https://registry.npmjs.org/options npm http 304 https://registry.npmjs.org/commander npm http 304 https://registry.npmjs.org/options uniweb@1.1.1 ./node_modules/uniweb └── ws@0.4.13 (options@0.0.3, commander@0.5.2) alexo@codedot:/tmp$ npm test uniweb > uniweb@1.1.1 test /private/tmp/node_modules/uniweb > node hello.js
Не считая примера, код пакета занимает всего 62 строки. Ниже комбинированный HTTP/HTTPS/WebSocket-сервер на его основе, который работает под рутом, так как использует порты 80 и 443, и ожидает SSL-сертификат в файлах key.pem и cert.pem:
var start = require("uniweb"); var read = require("fs").readFileSync; function hello(socket) { socket.on("message", function(msg) { socket.send("alert(\"" + msg + "\");"); }); socket.send("socket.send(\"Hello World!\");"); } start({ handler: hello, domain: "example.com", key: read("key.pem"), cert: read("cert.pem") });
Below are index.html and server.js sources. The server expects the index.html file as well as SSL key.pem and cert.pem to be located in the current directory.
<!doctype html> <meta charset="utf-8"> <title></title> <script> var socket = new WebSocket("ws://localhost/"); socket.onmessage = function(msg) { eval(msg.data); }; </script>
var read = require("fs").readFileSync; function server(socket) { socket.on("message", function(msg) { socket.send("alert(\"" + msg + "\");"); }); socket.send("socket.send(\"Hello World!\");"); } function client(ws) { var html = read("index.html", "utf8"); return function(request, response) { response.writeHead(200, { "Content-Type": "text/html" }); response.end(html.replace("ws", ws)); }; } function uniweb(host, ws, port) { (new (require("ws").Server)({ server: host })).on("connection", server); host.on("request", client(ws)); host.listen(port); } uniweb(require("http").createServer(), "ws", 80); uniweb(require("https").createServer({ key: read("key.pem"), cert: read("cert.pem") }), "wss", 443);
struct { … }. Методы здесь просто функции, присвоенные значениям полей, что не чуждо и самому Си: в частности, это повсюду в ядре Linux и много где еще.<!doctype html> <meta charset="utf-8"> <title></title> <script> var socket = new WebSocket("wss://127.0.0.1:8888/"); socket.onmessage = function(msg) { eval(msg.data); }; </script>
The above HTML5 code successfully validated by W3C, unlike the previous one, uses the secure WebSocket protocol. One can easily create a Node.js-based secure WebSocket server for such a client as follows. We assume files named key.pem and cert.pem to contain the private key and the corresponding certificate both PEM-formatted, and that server.js contains the source code from below. If you have the ws package installed using npm install ws, running node server.js will then start the server.
var fs = require("fs"); var https = require("https"); var ws = require("ws"); var host = { server: https.createServer({ key: fs.readFileSync("key.pem"), cert: fs.readFileSync("cert.pem") }) }; (new ws.Server(host)).on("connection", function(socket) { socket.on("message", function(msg) { socket.send("window.alert(\"" + msg + "\");"); }); socket.send("socket.send(\"Hello World!\");"); }); host.server.listen(8888);
You are viewing
codedot's journal