问题似乎是在GET连接升级到websocket之前发送消息正在尝试发生.我仍然试图追踪它,与此同时这是有效的.
#!/usr/bin/env perl
use MojolicIoUs::Lite;
use EV;
use AnyEvent;
#use POSIX qw(strftime);
get '/' => sub {
my $self = shift;
$self->render('main');
};
websocket '/echo' => sub {
my $self = shift;
my $w;
$self->on(finish => sub { Mojo::IOLoop->remove($w) });
# $self->send(strftime("Server $$: %a %b %e %H:%M:%S %Y",localtime));
$w = Mojo::IOLoop->recurring( 1 => sub{
$self->send('Got it');
});
};
app->start();
__DATA__
@@ main.html.ep
var ws = new WebSocket("to_abs %>");
ws.onopen = function () {
alert('Connection opened');
};
ws.onerror = function() { alert("Error"); };
ws.onmessage = function (msg) {
$("#tableID").find('tbody')
.append($('
').append($('
').text(msg.data)
)
);
};
请注意,在我的示例中,调试输出显示101个切换协议,而您的示例尝试自动调试echo.html.ep.
我还更改了模板以生成websocket url.
更新:
似乎为了连接到websocket,它必须订阅一个事件.在这个例子中,我订阅了完成事件,你想要做的就是停止计时器.
#!/usr/bin/env perl
use MojolicIoUs::Lite;
use EV;
use AnyEvent;
#use POSIX qw(strftime);
get '/' => sub {
my $self = shift;
$self->render('main');
};
websocket '/echo' => sub {
my $self = shift;
my $w;
$w = AE::timer 3,sub {
$self->send('Got it');
};
$self->on(finish => sub{ undef $w });
# $self->send(L<:controller>
};
app->start();
更新2:
The connection gets established when you respond to the WebSocket handshake with a 101 response status,which happens automatically if you subscribe to an event with
“on” or send a message with “send” right away.
这解释了情况.原始代码既不订阅事件也不立即发送.在几乎所有情况下,你至少会做到两个中的一个,在这种情况下:-)