DTSCode
DTSCode

Reputation: 1090

Asynchronous Chat Server using Mojolicious

Hello Ladies and Gentleman! I am currently writing a minimalistic chat server that will somewhat resemble IRC. I am writing it in perl using the Mojolicious, but unfortunately have run into an issue. I have the following code:

#!/usr/bin/perl

use warnings;
use strict;

use Mojo::IOLoop::Server;

my $server = Mojo::IOLoop::Server->new;

$server->on(accept => sub {
    my ($server, $handle) = @_;
    my $data;

    print $handle "Connected!\n";

    while(1) {
        $handle->recv($data, 4096);

        if($data) {
            print $server "$data";
        }
    }
});

$server->listen(port => $ARGV[0]);
$server->start;
$server->reactor->start unless $server->reactor->is_running;

Unfortunately, the print $server "$data"; line does not actually work. It gives off the error:

Mojo::Reactor::Poll: I/O watcher failed: Not a GLOB reference at ./server.pl line 20.

I have looked through the documentation for Mojolicious, but cannot find how to send the line I get from client A to the rest of the clients connected.

Upvotes: 3

Views: 560

Answers (1)

Dada
Dada

Reputation: 6626

While $handle is something like a stream you can write on, $server is a Mojo::IOloop::Server object, so it's not a surprise you can't write on it like you're trying to do.

Even if I use Mojolicious quite often, I'm not familiar with every possibilities (there are a lot), but here what I would suggest : you need to store a list of all connected clients (in a hash or an array for instance), and when you receive a message, you iterate through that client list, to send the message to all of them.

You also need a way (not hard to do) to delete clients from your clients list when they disconnect.

Also I'm not quite sure about your infinite loop : I wouldn't be surprised if it was blocking the server on the 1st connected client. It's better to use Mojolicious functions to do so :

$serv->on(message => sub { send the message to all clients });

And that function would be called every time a message is received.

Here is a good example, using Mojolicious::Light, pretty easy to understand I think : https://github.com/kraih/mojo/wiki/Writing-websocket-chat-using-Mojolicious-Lite

Upvotes: 3

Related Questions