express.io = express + socket.io
express.ioをインストールして、サーバーを立てるまで
### express.io install
package.json
{ "name": "test-webrtc", "version": "0.0.1", "private": true, "dependencies": { "express": "4.x", "ejs": "3.0.1", "express.io": "1.x", "coffee-script": "~1.6.3", "connect": "*" } }
$ npm update
### server.js
var express = require('express.io'); var app = express(); var PORT = 3000; var fs = require("fs"); var https = require("https"); var options = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('server.crt') } app.https(options).io(); console.log('server started' + PORT); app.use(express.static(__dirname + '/public')); app.get('/', function(req, res){ res.render('index.ejs'); }); app.io.route('ready', function(req){ req.io.join(req.data) app.io.room(req.data).broadcast('announce', { message: 'New client in the ' + req.data + ' room.' }) }) app.listen(PORT);
### index.ejs
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>WebRTC</title> <link rel="stylesheet" type="text/css" href="public/styles.css"> <script src="/socket.io/socket.io.js"></script> </head> <body> <p><button id="takeProfilePicture" type="button" autofocus="true">Create Profile Picture</button></p> <video id="videoTag" autoplay></video> <div> <label>Your Name</label><input id="myName" type="text"> <label>Your Name</label><input id="myMessage" type="text"> <input id="sendMessage" type="submit"> <div id="chatArea">Message: output:<br></div> </div> <script> navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || window.navigator.mozGetUserMedia; var constraints = {audio: false, video: { mandatory: { maxWidth: 240, maxHeight: 240 } } }; var videoArea = document.querySelector("video"); var myName = document.querySelector("#myName"); var myMessage = document.querySelector("#myMessage"); var sendMessage = document.querySelector("#sendMessage"); var chatArea = document.querySelector("#chatArea"); var ROOM = "chat"; io = io.connect(); io.emit('ready', ROOM); io.on('announce', function(data){ displayMessage(data.message); }); function displayMessage(message){ chatArea.innerHTML = chatArea.innerHTML + "<br>" + message; } navigator.getUserMedia(constraints, onSuccess, onError); function onSuccess(stream){ console.log("Success! we have a stream!"); // videoArea.src = window.URL.createObjectURL(stream); // videoArea.className = "grayscale_filter"; videoArea.srcObject = stream; } function onError(error){ console.log("Error with getUserMedia: ", error); } </script> </body> </html>
$npm server.js
socket ioとは、web soketにより、双方向通信を簡単に記述できる
複数ブラウザでテストし、io.emit(‘ready’, ROOM);となった際に、chatArea.innerHTML = chatArea.innerHTML + “
” + message;で、’New client in the ‘ + req.data + ‘ room.’が追加される