cyber-guard
cyber-guard

Reputation: 1846

Websockets and flushing with Mojolicious?

I am using the Mojolicious::Lite module to run a websockets server to handle the protocol. This is the testing code I am currently using for client:

socket.onopen = function(){$.each(proxies, function(){socket.send(this);});}
socket.onmessage = function(response){alert(response);}

And the server

websocket '/' => sub { 
    my $self = shift;
    $self->on(message => sub {
        my ($self, $message) = @_;
        my @info = split /-/,$message;

        $mech_proxy = WWW::Mechanize->new(timeout=>$info[1], autocheck=>0);
        $self->send(test_proxy($info[0]) => sub{sleep(int(rand(10)))});
    });
};
app->start;

Anyhow I thought that this would clearly avoid the need to flush the output, as originally I was actually doing just one send client side and then having the return message sent in a loop on server side; this didn't work because I wouldn't be able to flush the output and would have to wait for the loop to finish. However changing it around didn't help as I still have to wait until the last server side send is done and only then the data is sent to the client. Do you have any idea how I can get live 'updates' on the processing, i.e. output the server response as it is sent?

EDIT: I am getting mixed results with setTimout(socket.send(this),1000). What I figured is that probably in order to get the data flushed, new data must be sent only after the prior data has been processed and fully written on the server side. If this proves in fact right, it should be possible to write the client side so it only sends new data after it has received results from the previous data sent; this will achieve the effect of getting the desired 'live' updates.

Cheers

Upvotes: 4

Views: 1048

Answers (1)

cyber-guard
cyber-guard

Reputation: 1846

OK sorted it out, it was as said above new data must be sent only after receiving back response (code below). Also one note, surprisingly this way is actually faster than doing it with the jquery loop.

socket.onopen = function(){
    socket.send(proxies[0]+'-'+timeout);
    proxies.splice(0,1);
}

socket.onmessage = function(response){
    if (proxies.length > 0) {
        socket.send(proxies[0]+'-'+timeout);
        proxies.splice(0,1);
    }
document.write(response.data);
}

Upvotes: 1

Related Questions