WebSocket

WebSocket始めました。

701 views

サーバー

npm install websocket

でモジュールをインストールして、以下のコードを記述する。

var connections = [];
var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});

function originIsAllowed(origin) {
  // put logic here to detect whether the specified origin is allowed.
  return true;
}

wsServer.on('request', function(request) {
    if (!originIsAllowed(request.origin)) {
      // Make sure we only accept requests from an allowed origin
      request.reject();
      console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
      return;
    }

    var connection = request.accept('echo-protocol', request.origin);
    //接続ハンドルをリストに追加
    connections.push(connection);

    console.log((new Date()) + ' Connection accepted.');
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            //connection.sendUTF(message.utf8Data);
            broadcast(message);
        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
        connections = connections.filter(function(con){
            if(con != connection) {
                return true;
            }
            else {
                return false;
            }
        });
    });
});

function broadcast(message) {
    console.log("connections count " + connections.length);
    connections.forEach(function(con, i) {
        con.sendUTF(message.utf8Data);
    });
}
node app_server.js

でサーバーが起動する。

クライアント(html版)

<html>
    <head>
        <title>ソケットプログラム</title>
    </head>

    <body>

        <p id="message">未受信です。</p>
        <p id="recv_message"></p>
        <input type="text" id="send_msg">
        <input type="button" value="送信" onclick="sendMsg();">
        <script>
            var ws = new WebSocket('ws://localhost:8080/',['echo-protocol','soap', 'xmpp']);

            ws.onopen = function() {//WS接続確立
                document.getElementById("message").innerText = "接続しました";
                ws.send('hello');
             };

            // Log errors
            ws.onerror = function (error) {
              console.log('WebSocket Error ' + error);
            };

            // メッセージ受信
            ws.onmessage = function (e) {
                document.getElementById("message").innerText = "メッセージを受信しました";
                document.getElementById("recv_message").innerText = e.data;
              console.log('Server: ' + e.data);
            };

            function sendMsg() {
                var msg = document.getElementById("send_msg").value;
                ws.send(msg);
            }
            </script>

    </body>
</html>

この二つがあれば、チャットができる。

Page 1 of 2.

次のページ



[添付ファイル]


お問い合わせ

プロフィール

マッスル

自己紹介

本サイトの作成者。
趣味:プログラム/水耕栽培/仮想通貨/激辛好き
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
仮想通貨はNEMが好き。
水耕栽培は激辛好きが高じて、キャロライナ・リーパーの栽培にチャレンジ中。

サイト/ブログ

https://www.osumoi-stdio.com/pyarticle/

ツイッター

@darkimpact0626