You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl 6 UDP Socket客户端如何读取服务器响应?

How to Implement UDP Client-Server Response Handling in Perl 6

Great question! Let's break this down: Perl 6 fully supports bidirectional UDP communication—the gap in your current code is that neither the server is sending a response, nor the client is set up to listen for incoming packets. Let's fix both sides step by step.

Key Background: UDP Packets in Perl 6

When using IO::Socket::Async.bind-udp, the Supply you receive doesn't return raw strings—it returns Packet objects. Each Packet holds two critical details:

  • .data: the actual payload sent by the client (as a string)
  • .from: a tuple of (host, port) representing the client's address, so you can send a response back directly

Modified UDP Server (server-udp.pl)

This version will print the incoming message and send a response back to the client:

my $socket = IO::Socket::Async.bind-udp('localhost', 3333);
react {
    whenever $socket.Supply -> $packet {
        my $client-message = $packet.data;
        if $client-message.chars > 0 {
            say "Server received: $client-message";
            # Send a response to the client's address
            await $socket.send-to($packet.from[0], $packet.from[1], "Server response: Got your message!");
        }
    }
}

Modified UDP Client (client-udp.pl)

Now the client will send a message and listen for the server's response:

my $socket = IO::Socket::Async.udp();

# Send the initial message to the server
await $socket.print-to('localhost', 3333, "Hello, Perl 6!");

# Listen for incoming responses
react {
    whenever $socket.Supply -> $response-packet {
        say "Client received: " ~ $response-packet.data;
        # Exit the react block after getting the response
        done;
    }
}

How It Compares to Perl 5

Your Perl 5 example uses blocking recv to wait for a response. Perl 6 leans into its asynchronous model with react and Supply, which is more idiomatic for non-blocking I/O in the language. The core logic is identical:

  1. Send data to the server
  2. Wait for and process the server's response

The main difference is Perl 6's async approach, which avoids locking up the entire program while waiting for UDP packets.

Testing the Code

  1. Start the server first: perl6 server-udp.pl
  2. Run the client: perl6 client-udp.pl

You'll see:

  • Server output: Server received: Hello, Perl 6!
  • Client output: Client received: Server response: Got your message!

内容的提问来源于stack exchange,提问作者Shniperson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:18:55