LoginSignup
48
36

More than 5 years have passed since last update.

rubyでwebsocketを試してみる

Posted at

何かと耳にするwebsocketを簡易チャットアプリとして触ってみたときのメモ

環境


  • VirtualBox 4.3
  • ubuntu 14.04
  • ruby 2.2.0
  • em-websocket 0.5.1

websocketサーバをインストールする


$ gem install em-websocket

websoketサーバを起動する


websocket.rb
require 'em-websocket'
require 'pp'

connnections = []

EM::WebSocket.start({:host => "0.0.0.0", :port => 8888}) do |ws_conn|
  ws_conn.onopen do
    connnections << ws_conn
  end

  ws_conn.onmessage do |message|
    pp message
    connnections.each{|conn| conn.send(message) }
  end
end

※ポートを8888で起動します
※pp messageでサーバに送られてきたメッセージを標準出力します
※connnectionsに接続を格納し、connnections.eachで接続されたクライアント全てに
 メッセージを返すようにしています

$ ruby websocket.rb

クライアント(HTML)


websocket.html
<html>
<head><meta charset="UTF-8" />
<title>websocket ruby test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.3.min.js"></script> 
<script type="text/javascript">
$(function(){
    var ws = new WebSocket('ws://localhost:8888/');                                                                                                
    $("#send").on('click', function(){
        ws.send($('#message').val());
    });

    ws.onmessage = function(event){
        var message_li = $('<li>').text(event.data);
        $("#msg-area").append(message_li);
    };
});
</script>
</head>
<body>
<input type="text" id="message" />
<input type="button" id="send" value="send"/>
<ul id="msg-area" />
</body>
</html>

※HTMLが読み込まれると同時に、new WebSocket('ws://localhost:8888/')で
 websocket接続を確立します

異なる複数のブラウザを立ち上げ、片方でメッセージを入力し、ボタンをクリックすると
もう片方のブラウザ側にメッセージが表示されると思います。

48
36
0

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
48
36