#!/usr/bin/ruby # encoding: utf-8 require 'sinatra' require 'sinatra/reloader' require 'em-websocket' require 'set' require 'json' get '/' do erb :ws end get '/websocket' do clients = Set.new EM::WebSocket.start({:host => "0.0.0.0", :port => 8888}) do |ws_conn| ws_conn.onopen do clients << ws_conn printf("%d guest(s)\n", clients.length) end ws_conn.onmessage do |message| jvalue = JSON.parse(message) resp = ""+jvalue['name']+" 「"+jvalue['word']+"」" resp2 = ""+jvalue['name']+"さん 「"+jvalue['word']+"」" chat = Array.new clients.each{|conn| if (conn == ws_conn) conn.send(resp) else conn.send(resp2) end } end ws_conn.onclose do clients.delete(ws_conn) printf("%d GUEST(s)\n", clients.length) end EM::defer do puts "..captured!" loop do print("Enter message for all clients: ") line = gets puts("Sending") clients.each{|conn| conn.send(line.chomp) } end end end erb :index end __END__ @@ws <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>チャット</title> <style type="text/css"> </style> <script type="text/javascript" src="chat2.js" charset="utf-8"></script> </head> <body> <p>名前 <input name="name" id="name"> <p>一言 <input name="word" id="word"> </p> <button id="push" type="button" value="PUSH">送信</button> <p id="info">...</p> </body> </html> @@index <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <title>チャット</title> <style type="text/css"> </style> <script type="text/javascript" src="chat2.js" charset="utf-8"></script> </head> <body> <p>名前 <input name="name" id="name"> <p>一言 <input name="word" id="word"> </p> <button id="push" type="button" value="PUSH">送信</button> <p id="info">...</p> </body> </html>