2016년 12월 31일 토요일

html5 websocket and node.js websocketサーバ

html5のwebsocketとnode.jsのwebsocketサーバーを使い、双方向通信サンプル開発

・websocketTestというexpressプロジェクト生成
express websocketTest

・websocketモジュールインストール
npm install websocket

finalhandler とserve-staticモジュールインストール(localhost:3000/index.htmlのurlからindex.htmlを表示するため:こちらのモジュールがないとクライアントからindex.htmlをリクエストしてもサーバーではindex.htmlを返す処理がないため、index.htmlをレスポンスできない。index.htmlを返す処理を追加することもできるけど、こちらのモジュールをロードして実装することにする)

npm install finalhandler serve-static

-----------------------------------------------
server.js
-----------------------------------------------
var server = require('websocket').server
var http = require('http');

// localhost:3000/index.html --> 画面から直接htmlをリクエストするためのモジュールロード
var finalhandler = require('finalhandler');
var serveStatic = require('serve-static');
var serve = serveStatic("./");

// websocketサーバインスタンス生成し、待機
var socket = new server({

// httpサーバ生成
    httpServer: http.createServer(function(req, res){

// localhost:3000/index.html --> 画面から直接htmlをリクエスト
var done = finalhandler(req, res);
        serve(req, res, done);  
 
  // localhost:3000 --> htmlをレスポンスする処理
  // var fs = require('fs');
// fs.readFile("./index.html", function(errors, data){
// res.writeHead(200, {'Content-Type':'text/html'});
// res.end(data);
//});    
   
    }).listen(3000)  
});

/**
var socket = new server({
    httpServer: http.createServer().listen(3000)  
});
**/

var clients = [ ];

// websocketサーバーにリクエストイベントが発生した場合
socket.on('request', function(request) {

// コネクション取得
    var connection = request.accept(null, request.origin);

var index = clients.push(connection) - 1;

// メッセージを受信した場合の処理
       connection.on('message', function(message) {
   
        console.log(message.utf8Data);
       
        // クライアントからのメッセージを同一コネクションのすべてのクライアントに送信
        for (var i=0; i < clients.length; i++) {
            clients[i].sendUTF(message.utf8Data);
        }
                       
        //setTimeout(function() {
        //    connection.sendUTF('this is a websocket example');
        //}, 1000);
    });

// クライアントがコネクションを切った場合
    connection.on('close', function(connection) {
        console.log('connection closed');
    });
});


-----------------------------------------------
index.html
-----------------------------------------------
<html>
<head>
<style type="text/css">
#msg{
background-color:pink;
}

#content{
background-color:lightgray;
width:500px;
height:200px;
overflow:scroll;
}

#server{
color:red;
}

</style>
</head>
<body>
<div>Enjoy Chat</div>

<div id="content" ></div>

<input type="text"  id="msg" size="50"/><button id="btn">message send...</button></input>

<script type="text/javascript">
 
(function (){
document.getElementById("btn").onclick = send;
var msgEl = document.getElementById("msg");
// 入力欄にフォーカス設定
msgEl.focus();
// キープレスイベントハンドラ登録
msgEl.onkeypress = function(){
if(event.keyCode === 13){
send();
}
}
var chat = document.getElementById('content');

// websocketインスタンス生成
var ws = new WebSocket("ws://localhost:3000/");

// サーバー接続
ws.onopen = function() {
debugger;
console.log('サーバーに接続完了');
}

// 送信処理
function send(){
var msg = document.getElementById('msg').value;
ws.send(msg);
// スクロール調整(直近のメッセージが見えるように)
chat.scrollTop = chat.scrollHeight;
// メッセージ送信完了したら、入力欄をクリア
document.getElementById('msg').value = "";
}

// サーバから受信
ws.onmessage = function(message){
var msgFromSever = message.data;
var attr = {id:'server'};
append(chat, 'P', "from server : " + msgFromSever, attr);
}

// chat内容追加
function append(parent, createTag, text, attr){
// 指定タグ要素を作成、内容をノードに追加
var node = document.createElement(createTag);
var textNode = document.createTextNode(text);
for( key in attr){
node[key] = attr[key];
}
//node['id'] = id;
//node.style = 'color:blue;'
node.appendChild(textNode);
// 親要素に子ノード追加
parent.appendChild(node);
}

})();
   
</script>
</body>
</html>

-----------------------------------------------------
・サーバ開始
node server.js

・url
http://127.0.0.1:3000/index.html




댓글 없음:

댓글 쓰기