Forum: Ruby Need some help to implement something in eventmachine.

Posted by Eliezer Croitoru (Guest)
on 2012-07-12 23:38
(Received via mailing list)
I wrote my server in pure eventmachine source at:
https://github.com/elico/echelon

i am struggling to understand something.
in eventmachine i have "receive_data" method with a "data" variable and
the send_data(data) method.

i have implemented the server logic as :
##
def post_init
  cleanup_all_data
end

def receive_data(data)
  #data parsing code
  send_data(response)
  cleanup_all_data
end
##

but do i really need to cleanup data? if it's a tcp socket and non
persistent connection then it's a dedicated connection and when it's
closed all the data is dead? or it's an endless loop i need to cleanup
the data for the next connection?

Thanks,
Eliezer
Posted by Alan Schwarz (luxdormiens)
on 2012-07-14 07:05
(Received via mailing list)
Hi,

I have the happy circumstance of having used EventMachine recently and I
think I can answer your question below.

On Thu, Jul 12, 2012 at 2:37 PM, Eliezer Croitoru 
<eliezer@ngtech.co.il>wrote:

>         cleanup_all_data
> persistent connection then it's a dedicated connection and when it's closed
> all the data is dead? or it's an endless loop i need to cleanup the data
> for the next connection?
>
>
post_init is used to initialize variables after instantiating the 
server,
so all the instance variables will not point to nil.

Secondly, in the EventMachine rdoc describing receive_data, EventMachine
*knows absolutely nothing about the protocol which your code 
implements*.
What it means is that you must define how receive_data will separate the
data stream because it otherwise will not know where the stream ends.
Notice that the code is using pos =~ /\r\n\r\n/ followed by
@icap_header[:data] = @data[0..pos+1] to cap the stream and then calling
cleanup to start over for a new stream.

This all happens on the same connection. A new connection would use a 
new
server instance with its own instance variables.

You could try instead using the BufferedTokenizer class, which will 
split
the received data into an array of tokenized entities using a delimiter
(the default is "\n", but in this case you would use "\r\n\r\n"). You 
can
then iterate through the array using the each method, passing your code 
as
a block.

Lastly, there is a forum for EventMachine at
https://groups.google.com/forum/?fromgroups#!forum...
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.