Recently, the task before me was to write a small chat demon for a large Internet project. I solved this problem using Ruby and Event Machine. Details and a small example under the cut.
After a trial version of the chat written on native Ruby sockets, it became clear that it would not work for a sufficiently large load. Plus, it worked unstably. I made decisions to optimize the code. The search for the necessary information on the topic was not particularly successful, then I decided to visit the project’s
thin page to find out how this web server was made and on this page I came across a link to the
Event Machine - a networked I / O library with extremely high scalability, performance and stability . I was impressed with the promises and decided to try.
')
As I understood from the
Event Machine documentation , the library does not use native Ruby sockets and implements a different approach when working with the network, and also provides an event-driven programming model.
So, let's start creating the easiest chat server on EventMachine. To get started, you need to install gems:
sudo gem install eventmachine
I will cite the code with comments right away:
require 'rubygems'
require 'eventmachine'
module ChatLogic
@@connections = [] #
#
def post_init
@@connections << self
end
#
def receive_data data
#
@@connections.each{ |connection| connection.send_data data }
end
#
def unbind
@@connections.delete(self)
end
end
#
EventMachine::run {
host,port = "0.0.0.0", 8090
EventMachine::start_server host, port, ChatLogic
puts "Listening #{host}:#{port}..."
}
Highlighted code on github.As you can see, the third parameter in the EventMachine :: start_server method is the name of the module that contains the declaration of the protocol or user functionality. This module will be mixed-in into the EventMachine :: Connection class.
Also in the ChatLogic module, three methods are redefined that EventMachine will automatically call upon the occurrence of the corresponding events: post_init, receive_data (data), unbind, which are initiated to connect when connecting, receiving data and breaking. Of course, in the module, you can define other methods and classes to implement the logic of the server, but you will need to call them yourself.
So, I brought the code for the simplest, but fast and stable Ruby chat server using the Event Machine library, which seems to be worthy of the attention of programmers and, by the way, is available not only for Ruby.