Pergunta

 require 'eventmachine'

  module EchoServer
    def post_init
      puts "-- someone connected to the echo server!"
    end

    def receive_data data
      send_data ">>>you sent: #{data}"
      close_connection if data =~ /quit/i
    end

    def unbind
      puts "-- someone disconnected from the echo server!"
    end
  end

  class Test
    attr_reader :some_value
    def start
      EventMachine::run {
      EventMachine::start_server "127.0.0.1", 8081, EchoServer
      }
    end
  end

My question is how to get some_value in EchoServer module? and what's the relation between class Test and module EchoServer ?

Foi útil?

Solução

If you change your EchoServer into a class and add an attr_accessor for some_value you can can then attach a block to the start server and pass the value in.

#!/usr/bin/env ruby

require 'rubygems'
require 'eventmachine'

class EchoServer < EM::Connection
  attr_accessor :some_value
  def post_init
    puts "blah with #{some_value}"
  end

  def receive_data(data)
   puts "#{some_value} received #{data}"
  end

  def unbind
   puts "unbound"
  end
end

v = "some_value"
EM.run do
  EM.start_server "127.0.0.1", 8081, EchoServer do |conn|
    conn.some_value = v
  end
end

In your example the only relation between Test and EchoServer is that you ran the EM event loop from inside the test class. This has no effect on EM or how it will use EchoServer.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top