マウスサーバー

JRubyで起動して、telnet localhost 5000で接続して 50,100 とか入力するとマウスが動く

#!/usr/bin/env jruby
## telnet localhost 5000 and put "50,100"

require 'java'
import 'java.awt.Robot'
require 'rubygems'
require 'eventmachine'

PORT = 5000

@@channel = EM::Channel.new
@@robot = Robot.new

class MouseServer < EM::Connection
  def post_init
    @sid = @@channel.subscribe{|msg|
      send_data msg
    }
    puts "new client <#{@sid}>"
  end
  def receive_data data
    ## マウスを移動
    data.strip!
    unless data =~ /^\d+ *, *\d+$/
      puts "data error : #{data}"
      return
    end
    x, y = data.split(/ *, */).map{|xy|xy.to_i}
    puts "move - x:#{x},y:#{y}"
    @@robot.mouse_move(x, y)

    ## 現在位置を全clientに送信
    mouse = java.awt.MouseInfo.pointer_info.location
    @@channel.push "#{mouse.x},#{mouse.y}\n"
  end
  def unbind
    puts "unbind <#{@sid}>"
    @@channel.unsubscribe @sid
  end
end

EM::run do
  EM::start_server('0.0.0.0', PORT, MouseServer)
  puts "start server - port:#{PORT}"
  EM::defer do
    loop do
      mouse = java.awt.MouseInfo.pointer_info.location
      puts "x:#{mouse.x},y:#{mouse.y}"
      @@channel.push "#{mouse.x},#{mouse.y}\n"
      sleep 0.1
    end
  end
end