Sending and receiving UDP while accepting stdin, with just selectors:
import std/[net, selectors, strformat, strutils]
const
cfgMaxPacket = 500
cfgPort = 8800
localhost = "127.0.0.1"
let
socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
events = newSelector[int]()
socket.bindAddr(Port(cfgPort), localhost)
events.registerHandle(socket.getFd, {Read}, 0)
events.registerHandle(0, {Read}, 0) # stdin
echo &"Listening to stdin and {localhost}:{cfgPort}"
while true:
for got in events.select(-1):
if got.fd == cast[int](socket.getFd):
var
message, srcAddress = ""
srcPort = Port(0)
discard socket.recvFrom(message, cfgMaxPacket, srcAddress, srcPort)
echo "got UDP: ", message.strip
elif got.fd == 0:
# send packet to ourselves
try:
socket.sendTo(localhost, Port(cfgPort), stdin.readLine())
except EOFError:
quit()
Run
What you type interactively is sent and then received over UDP, and then
printed. While you're doing this you can `nc -u 127.0.0.1 8800` in another
window and send packets with netcat that'll be printed in the same manner.
The .strip is for the newlines that netcat will send.