241
229

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

5分で動かせるwebsocketのサンプル3つ

Last updated at Posted at 2018-03-21

サンプル1

ほぼ参考動画と同じですが、自分も簡単にできましたので、コードをのせておきます!

参考
【WebSocket Tutorial】
https://www.youtube.com/watch?v=X7j6raOVXuU&list=PLYxzS__5yYQnRizvwNYWwzFjd9J4ni_Ga

mkdir server
cd server
npm init -y
npm i ws --save
touch index.js

index.jsの内容

index.js
var server = require('ws').Server;
var s = new server({port:5001});

s.on('connection',function(ws){

    ws.on('message',function(message){
        console.log("Received: "+message);

        s.clients.forEach(function(client){
            client.send(message+' : '+new Date());
        });
    });

    ws.on('close',function(){
        console.log('I lost a client');
    });

});
$ node index.js

どこでもいいので、index.htmlを作成し、ブラウザで開く

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <input type="button" id="sample" value="送信">

    <script>
        var sock = new WebSocket('ws://127.0.0.1:5001');

        // 接続
        sock.addEventListener('open',function(e){
            console.log('Socket 接続成功');
        });

        // サーバーからデータを受け取る
        sock.addEventListener('message',function(e){
            console.log(e.data);
        });

        document.addEventListener('DOMContentLoaded',function(e){
            // サーバーにデータを送る
            document.getElementById('sample').addEventListener('click',function(e){
                sock.send('hello');
            });
        });
    </script>
</body>
</html>

9uKELtbgf6.gif

すごい!!

サンプル2

socket.ioのGet Startedを読むと簡単に作れる!

【Get Started: Chat application】
https://socket.io/get-started/chat/

以下はソースコードコピペです。

package.json作成

{
  "name": "socket-chat-example",
  "version": "0.0.1",
  "description": "my first socket.io app",
  "dependencies": {
    "express": "^4.15.2",
    "socket.io": "^1.7.3"
  },
  "scripts": {
    "start": "node index.js"
  }
}
$ npm i --save
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(port, function(){
  console.log('listening on *:' + port);
});
<!doctype html>
<html>
  <head>
    <title>Socket.IO chat</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
      #messages { margin-bottom: 40px }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>
    <!-- ↓の書き方に修正しました <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script> -->
    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
      $(function () {
        var socket = io();
        $('form').submit(function(){
          socket.emit('chat message', $('#m').val());
          $('#m').val('');
          return false;
        });
        socket.on('chat message', function(msg){
          $('#messages').append($('<li>').text(msg));
          window.scrollTo(0, document.body.scrollHeight);
        });
      });
    </script>
  </body>
</html>
$ npm run start

BV5wwPOJao.gif

すごい!!

サンプル3

Node-REDを使用する

IBM Cloud(bluemix)のアカウントが必要ですが、参考サイト通りにやると簡単にできました!

【Node-RED を使用してリアルタイムのチャット・アプリケーションを 5 分で作成する】
https://www.ibm.com/developerworks/jp/cloud/library/cl-rtchat-app/

コードをインポートするためのjsonを入手する

[{"id":"bc740d23.438bf","type":"websocket-listener","path":"/ws/chat","wholemsg":"false"},{"id":"759c5b9e.8a63a4","type":"websocket in","name":"","server":"bc740d23.438bf","x":99,"y":48,"z":"601d19ea.9fe2e8","wires":[["4b79826c.b4867c"]]},{"id":"4b79826c.b4867c","type":"function","name":"","func":"delete msg._session;\nreturn msg;\n\n","outputs":1,"x":273,"y":48,"z":"601d19ea.9fe2e8","wires":[["a45971fa.5ba69"]]},{"id":"a45971fa.5ba69","type":"websocket out","name":"","server":"bc740d23.438bf","x":454,"y":48,"z":"601d19ea.9fe2e8","wires":[]},{"id":"901a91c.f6fe57","type":"http in","name":"","url":"/chat","method":"get","x":107,"y":116,"z":"601d19ea.9fe2e8","wires":[["51a55cc7.ae5aa4"]]},{"id":"51a55cc7.ae5aa4","type":"template","name":"","field":"","template":"<head>\n  <meta name=\"viewport\" content=\"width=320, initial-scale=1\">\n  <title>Chat</title>\n</head>\n\n<body>\n  <div id=\"wrapper\">\n    <div id=\"chat_box\" class=\"content\"></div>\n\n    <div id=\"footer\">\n      <div class=\"content\">\n        <input type=\"text\" id=\"user\" placeholder=\"Who are you?\" />\n        <input type=\"text\" id=\"message\" placeholder=\"What do you want to say?\" />\n        <input type=\"button\" id=\"send_btn\" value=\"Send\" onclick=\"sendMessage()\">\n      </div>\n    </div>\n  </div>\n</body>\n\n<script type=\"text/javascript\">\n  var wsUri = \"wss://{{req.headers.host}}/ws/chat\";\n  var ws = new WebSocket(wsUri);\n\n  function createSystemMessage(message) {\n    var message = document.createTextNode(message);\n\n    var messageBox = document.createElement('p');\n    messageBox.className = 'system';\n\n    messageBox.appendChild(message);\n\n    var chat = document.getElementById('chat_box');\n    chat.appendChild(messageBox);\n  }\n\n  function createUserMessage(user, message) {\n    var user = document.createTextNode(user + ': ');\n\n    var userBox = document.createElement('span');\n    userBox.className = 'username';\n    userBox.appendChild(user);\n\n    var message = document.createTextNode(message);\n\n    var messageBox = document.createElement('p');\n    messageBox.appendChild(userBox);\n    messageBox.appendChild(message);\n\n    var chat = document.getElementById('chat_box');\n    chat.appendChild(messageBox);\n  }\n\n  ws.onopen = function(ev) {\n    createSystemMessage('[Connected]');\n  };\n\n  ws.onclose = function(ev) {\n    createSystemMessage('[Disconnected]');\n  }\n\n  ws.onmessage = function(ev) {\n    var payload = JSON.parse(ev.data);\n    createUserMessage(payload.user, payload.message);\n\n    var chat = document.getElementById('chat_box');\n    chat.scrollTop = chat.scrollHeight;\n  }\n\n  function sendMessage() {\n    var user = document.getElementById('user');\n    var message = document.getElementById('message');\n\n    var payload = {\n      message: message.value,\n      user: user.value,\n      ts: (new Date()).getTime()\n    };\n\n    ws.send(JSON.stringify(payload));\n    message.value = \"\";\n  };\n</script>\n\n<style type=\"text/css\">\n  * {\n    font-family: \"Palatino Linotype\", \"Book Antiqua\", Palatino, serif;\n    font-style: italic;\n    font-size: 24px;\n  }\n\n  html, body, #wrapper {\n    margin: 0;\n    padding: 0;\n    height: 100%;\n  }\n\n  #wrapper {\n    background-color: #ecf0f1;\n  }\n\n  #chat_box {\n    box-sizing: border-box;\n    height: 100%;\n    overflow: auto;\n    padding-bottom: 50px;\n  }\n\n  #footer {\n    box-sizing: border-box;\n    position: fixed;\n    bottom: 0;\n    height: 50px;\n    width: 100%;\n    background-color: #2980b9;\n  }\n\n  #footer .content {\n    padding-top: 4px;\n    position: relative;\n  }\n\n  #user { width: 20%; }\n  #message { width: 68%; }\n  #send_btn {\n    width: 10%;\n    position: absolute;\n    right: 0;\n    bottom: 0;\n    margin: 0;\n  }\n\n  .content {\n    width: 70%;\n    margin: 0 auto;\n  }\n\n  input[type=\"text\"],\n  input[type=\"button\"] {\n    border: 0;\n    color: #fff;\n  }\n\n  input[type=\"text\"] {\n    background-color: #146EA8;\n    padding: 3px 10px;\n  }\n\n  input[type=\"button\"] {\n    background-color: #f39c12;\n    border-right: 2px solid #e67e22;\n    border-bottom: 2px solid #e67e22;\n    min-width: 70px;\n    display: inline-block;\n  }\n\n  input[type=\"button\"]:hover {\n    background-color: #e67e22;\n    border-right: 2px solid #f39c12;\n    border-bottom: 2px solid #f39c12;\n    cursor: pointer;\n  }\n\n  .system,\n  .username {\n    color: #aaa;\n    font-style: italic;\n    font-family: monospace;\n    font-size: 16px;\n  }\n\n  @media(max-width: 1000px) {\n    .content { width: 90%; }\n  }\n\n  @media(max-width: 780px) {\n    #footer { height: 91px; }\n    #chat_box { padding-bottom: 91px; }\n\n    #user { width: 100%; }\n    #message { width: 80%; }\n  }\n\n  @media(max-width: 400px) {\n    #footer { height: 135px; }\n    #chat_box { padding-bottom: 135px; }\n\n    #message { width: 100%; }\n    #send_btn {\n      position: relative;\n      margin-top: 3px;\n      width: 100%;\n    }\n  }\n</style>\n","x":273,"y":116,"z":"601d19ea.9fe2e8","wires":[["35605d04.ca9fa2"]]},{"id":"35605d04.ca9fa2","type":"http response","name":"","x":416,"y":116,"z":"601d19ea.9fe2e8","wires":[]}]

あとは参考サイトの手順通り行いました。

S8f9GMt6oZ.gif

すごい!!


最後まで見ていただいてありがとうございました m(_ _)m

241
229
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
241
229

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?