in reply to Mixing asynchronous data feed with synchronous program flow control
Only FWIW and good measure.
Server:
holli
You can lead your users to water, but alas, you cannot drown them.
Server:
Client:use Cro::HTTP::Router; use Cro::HTTP::Server; use Cro::HTTP::Router::WebSocket; my $application = route { get -> { web-socket -> $incoming { supply { my Bool $Running; multi sub process-command( "RUN" ) { True, ( $Running ?? "Already running" !! "Starting + to run…" ); } multi sub process-command( "STOP" ) { False, ( $Running ?? "Stopping…" !! "Not running" +); } multi sub process-command( $command ) { $Running, "Unknown command: $command"; } emit "Connected… RUN|STOP\n" ~ "Service is { $Running ?? "already" !! "not" } ru +nning"; whenever $incoming -> $message { my $command = await $message.body-text; say "Command: $command"; ($Running, my $answer) = process-command( $command + ); emit $answer; } } } } } my Cro::Service $service = Cro::HTTP::Server.new( :host<localhost>, :port<8080>, :$application ); $service.start; say "Started"; react whenever signal(SIGINT) { say "Killed"; $service.stop; exit; }
use Cro::WebSocket::Client; say "Connecting..."; my $conn = try await Cro::WebSocket::Client.connect( 'ws://localhost:8 +080' ); say "WebSocket handshake failed!" and exit unless $conn; say "Connected"; react { # It is guarantueed, only one whenever block in this react block c +an be running at any given time # There are no race conditions, for $conn whenever $conn.messages -> $message { say "Incoming: ", await $message.body; } # Currently this part only works for me since I patched in the clo +sing - supply. # But I am confident my pull request will be accecpted in some for +m # Maybe not with that exact name whenever $conn.closing -> $reason { say "Closing: $reason"; done; } # Without the above, one would have to check here for # $conn.closed != True before calling `send` whenever Supply.interval(5) -> $tick { my $command = ("RUN", "STOP").pick; say "Sending: $command"; $conn.send( $command ); CATCH { say "Error sending <$command>: {.message}" } } };
holli
You can lead your users to water, but alas, you cannot drown them.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Mixing asynchronous data feed with synchronous program flow control (in Raku)
by Your Mother (Archbishop) on Jan 03, 2020 at 23:39 UTC | |
by jcb (Parson) on Jan 04, 2020 at 00:41 UTC | |
by Your Mother (Archbishop) on Jan 04, 2020 at 02:58 UTC |
In Section
Seekers of Perl Wisdom