備忘録(websocket)

備忘録

http://www.atmarkit.co.jp/ait/articles/1603/14/news015.html
websocket の導入

$ sudo apt install nodejs-legacy
$ sudo apt install npm

~$ node -v
v4.2.6
~$ npm -v
3.5.2

を確認

~/websocket-chat$ npm install socket.io

~/websocket-chat/node_modules/socket.io
が出来たことを確認

websocket-chat/app.js
websocket-chat/index.html

を追加

//index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>websocket-chat</title>
  <link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  <script type="text/javascript" src="/socket.io/socket.io.js"></script>
</head>
<body>
  <div class="container">
    <h1>WebSocket-Chat</h1>
      <form class="form-inline">
        <div class="form-group">
          <label for="msgForm">メッセージ:</label>
          <input type="text" class="form-control" id="msgForm">
        </div>
          <button type="submit" class="btn btn-primary">送信</button>
      </form>
      <div id="chatLogs"></div>
  </div>
    
    <script type="text/javascript">
        var socket = io.connect();
    
        socket.on("server_to_client", function(data){appendMsg(data.value)});
    
        function appendMsg(text) {
            $("#chatLogs").append("<div>" + text + "</div>");
        }
    
        $("form").submit(function(e){
            var message = $("#msgForm").val();
            $("#msgForm").val('');
            socket.emit("client_to_server", {value : message});
            e.preventDefault();
        });
    </script>
</body>
</html>
//app.js
var http = require('http');
var socketio = require('socket.io');
var fs = require('fs');
var server = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type' : 'text/html'});
    res.end(fs.readFileSync(__dirname + '/index.html', 'utf-8'));
}).listen(3000);  // ポート競合の場合は値を変更
 
var io = socketio.listen(server);
 
io.sockets.on('connection', function(socket) {
    socket.on('client_to_server', function(data) {
        io.sockets.emit('server_to_client', {value : data.value});
    });
});

~/websocket-chat$ node app.js
の後
http://localhost:3000/
に2つの画面からアクセス