NodeJSのWebSocketで入力内容の送受信

コマンド

$ npm init
$ npm i websocket
$ node server.js #サーバー動かす

コード

server.js
var http = require('http');
var WSServer = require('websocket').server;
var url = require('url');
var clientHtml = require('fs').readFileSync('test.html');

var plainHttpServer = http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html'});
    res.end(clientHtml);
}).listen(8888);

var webSocketServer = new WSServer({httpServer: plainHttpServer});
var accept = ['localhost', '127.0.0.1'];

webSocketServer.on('request', function (req) {
    req.origin = req.origin || '*';
    if (accept.indexOf(url.parse(req.origin).hostname) === -1) {
        req.reject();
        console.log(req.origin + ' access not allowed.');
        return;
    }

    var connection = req.accept(null, req.origin);
    console.log((new Date()) + ' Connection accepted.');

    connection.on('message', function(message) {
            //if(msg.utf8Data === 'Hello'){}
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF("<Echo>"+message.utf8Data);
            //websocket.send('sended from WebSocket Server');
    });

    connection.on('close', function (code,desc) {
        console.log('connection released! :' + code + ' - ' + desc);
    });
});
test.html
<html>
<head>
   <title>タイトル</title>
   <meta charset="utf-8">
</head>
<body>

<script>
var ws = new WebSocket("ws://localhost:8888");
ws.onmessage = function(e) {
   console.log("OnMessage:"+e.data);
};
ws.onclose = function (e) {
   console.log(e.code+"/"+e.type);
};

//1秒ごとに入力内容を送る
function sendData(){
   ws.send( document.getElementById('message').value );
}
setInterval(sendData, 1000);
</script>

<input id="message" type="text" value="フロント送信データ" />
<button onClick="sendData()">送信</button>

</body>
</html>