使用“cro sub”创建了一个 websocket 服务器。
写了这个客户:
use v6;
use Cro::WebSocket::Client;
constant WS-PORT = '20000';
constant WS-ADDRESS = 'localhost';
constant WS-PATH = 'chat';
constant WS-URL = 'ws://' ~ WS-ADDRESS ~ ':' ~ WS-PORT ~ '/' ~ WS-PATH;
constant TIMEOUT-TO-CONNECT = 5; # seconds
my $timeout;
my $connection-attempt;
await Promise.anyof(
$connection-attempt = Cro::WebSocket::Client.connect(WS-URL),
$timeout = Promise.in(TIMEOUT-TO-CONNECT));
if $timeout.status == Kept
{
say "* could not connect to server in ', TIMEOUT-TO-CONNECT, ' seconds";
exit 1;
}
if $connection-attempt.status != Kept
{
say "* error ", $connection-attempt.cause,
" when trying to connect to server";
exit 1;
}
my $connection = $connection-attempt.result;
my $peer = WS-ADDRESS ~ ':' ~ WS-PORT;
say '* connected with ', $peer;
my $counter = 0;
my $message-supplier = Supplier::Preserving.new;
my $has-message-to-send = $message-supplier.Supply;
$message-supplier.emit(1);
react
{
whenever $has-message-to-send
{
$counter++;
$connection.send($counter);
say "* ok, sent message ", $counter, " to server";
}
whenever $connection.messages -> $reply
{
say '* received reply=[' ~ $reply ~ '] from server';
$message-supplier.emit(1);
}
} # react
我使用 tcpdump 看到来自服务器的响应代码 101(切换协议),但我没有看到从客户端发送到服务器的消息。
那么,我做错了什么?
另一个问题,"$connection.send" 不应该返回一个 Promise 什么的吗?发送时出现错误怎么办?
还有一个问题:似乎服务器只理解 IPV6 地址......如何让它理解 IPV4 地址?
就是这样,现在。
更新
按照 Takao 的建议,改变
$connection.send($counter)
到
$connection.send($counter.Str)
解决了这个问题(虽然我在另一个程序上试过,不是这个)。