Reputation: 4780
I have developed multiple eventmachine servers which are like
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
EventMachine::run {
EventMachine::start_server "127.0.0.1", 8081, EchoServer
EventMachine::start_server "127.0.0.1", 8082, EchoServer
EventMachine::start_server "127.0.0.1", 8083, EchoServer
}
Now I need to send data to the client as per the port only 8082. If I have all the connections open . Server needs to send back data to the perticular server. So If From 8081 I get the request I need to send it to 8082 client. How do I send that?
Upvotes: 1
Views: 1074
Reputation: 14082
According to the modification of the original question, I posted a new answer.
You will need to track the server port
for each connection. And when a new connection is established from port 8082, store that connection until it is closed. And when you get data from clients connected by 8081 port, send data to all connections stored before.
require 'eventmachine'
$clients = []
module EchoServer
def initialize(port)
@port = port
end
def post_init
puts "-- someone connected to the echo server!"
$clients << self if @port == 8082
end
def receive_data data
send_data ">>>you sent: #{data}"
# data is from a client connected by 8081 port
if @port == 8081
$clients.each do |c|
c.send_data ">>>server send: #{data}"
end
end
close_connection if data =~ /quit/i
end
def unbind
puts "-- someone disconnected from the echo server!"
$clients.delete self if @port == 8082
end
end
# Note that this will block current thread.
EventMachine.run {
# arguments after handler will be passed to initialize method
EventMachine.start_server "127.0.0.1", 8081, EchoServer, 8081
EventMachine.start_server "127.0.0.1", 8082, EchoServer, 8082
EventMachine.start_server "127.0.0.1", 8083, EchoServer, 8083
}
Upvotes: 3
Reputation: 14082
Run telnet 127.0.0.1 8082
under you console/shell.
-> ~ $ telnet 127.0.0.1 8082
Trying 127.0.0.1...
Connected to localhost.localdomain (127.0.0.1).
Escape character is '^]'.
hello
>>>you sent: hello
quit
Connection closed by foreign host.
If you want to send data from Ruby code, take a look at socket
library.
require 'socket'
s = TCPSocket.new '127.0.0.1', 8082
s.puts "Hello"
puts s.gets #=> >>>you sent: Hello
s.close
Upvotes: 2