Created
August 6, 2013 06:30
-
-
Save hnaohiro/6162524 to your computer and use it in GitHub Desktop.
RubyでWebカメラを使い、WebSocketで配信する最小のコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'opencv' | |
require 'em-websocket' | |
require 'base64' | |
class WebCam | |
def initialize(n = 0) | |
@cap = OpenCV::CvCapture.open(n) | |
end | |
def get_with_base64 | |
mat = @cap.query.to_CvMat | |
Base64.encode64(mat.encode('.jpg').pack('C*')) | |
end | |
end | |
EM::run do | |
raise ArgumentError if ARGV.size == 0 | |
webCam = WebCam.new(ARGV[0].to_i) | |
connections = Array.new | |
EM::WebSocket.start(:host => '0.0.0.0', :port => 51234) do |ws| | |
ws.onopen do |handshake| | |
puts 'connected from ' + get_ip(ws) | |
connections.push(ws) | |
end | |
ws.onclose do |handshake| | |
puts 'closed from ' + get_ip(ws) | |
connections.delete(ws) | |
end | |
end | |
EM::defer do | |
loop do | |
sleep 0.1 | |
next if connections.size == 0 | |
image = webCam.get_with_base64 | |
connections.each do |con| | |
con.send(image); | |
end | |
end | |
end | |
def get_ip(con) | |
if con.get_peername == nil | |
'unknown' | |
else | |
_, ip = Socket.unpack_sockaddr_in(con.get_peername) | |
ip | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment