recvfrom
recvfrom(socket::UDPSocket) -> (address, data)
Read a UDP packet from the specified socket, returning a tuple of (address, data), where address will be either IPv4 or IPv6 as appropriate.
Examples
-
Receive UDP packet and extract address and data:
julia> sock = UDPSocket(); julia> bind(sock, "127.0.0.1", 12345); julia> (address, data) = recvfrom(sock); julia> address "127.0.0.1" julia> data "Hello, World!"
In this example, we create a UDP socket, bind it to a specific address and port, and then use
recvfrom
to receive a UDP packet. The function returns a tuple containing the address from which the packet was received and the packet data. -
Receive UDP packet and ignore address:
julia> sock = UDPSocket(); julia> bind(sock, "0.0.0.0", 12345); julia> (_, data) = recvfrom(sock); julia> data "Hello, World!"
In this example, we use the underscore
_
to ignore the address returned byrecvfrom
and only store the packet data. - Handle multiple UDP packets:
julia> sock = UDPSocket(); julia> bind(sock, "0.0.0.0", 12345); julia> for _ in 1:5 (address, data) = recvfrom(sock); println("Received packet from $address: $data") end
This example demonstrates receiving multiple UDP packets in a loop. Each time
recvfrom
is called, it blocks until a packet is received. The address and data are then printed.
Common mistake example:
julia> sock = UDPSocket();
julia> (address, data) = recvfrom(sock);
ERROR: UndefVarError: UDPSocket not defined
In this example, the UDPSocket
type is not defined because the Sockets
module has not been imported. Make sure to import the necessary modules before using the functions they provide.
See Also
accept, bind, :@spawn, connect, fetch, getaddrinfo, gethostname, getipaddr, getsockname, init_worker, IPv4, IPv6, isready, issocket, kill, listen, recv, recvfrom, remotecall, remotecall_fetch, remotecall_wait, RemoteRef, send, setopt,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.