Adding more UDP support + example.

This commit is contained in:
Brad Nelson
2022-08-10 23:41:40 -07:00
parent 71109e3880
commit 00c6a87228
4 changed files with 73 additions and 0 deletions

View File

@ -88,6 +88,8 @@ forth definitions
vocabulary sockets sockets definitions
transfer sockets-builtins
1 constant SOCK_STREAM
2 constant SOCK_DGRAM
3 constant SOCK_RAW
2 constant AF_INET
16 constant sizeof(sockaddr_in)
1 constant SOL_SOCKET

View File

@ -389,6 +389,12 @@ static cell_t TimerIsrRegister(cell_t group, cell_t timer, cell_t xt, cell_t arg
YV(sockets, sockaccept, n0 = accept(n2, (struct sockaddr *) a1, (socklen_t *) a0); NIPn(2)) \
YV(sockets, select, n0 = select(n4, (fd_set *) a3, (fd_set *) a2, (fd_set *) a1, (struct timeval *) a0); NIPn(4)) \
YV(sockets, poll, n0 = poll((struct pollfd *) a2, (nfds_t) n1, n0); NIPn(2)) \
YV(sockets, send, n0 = send(n3, a2, n1, n0); NIPn(3)) \
YV(sockets, sendto, n0 = sendto(n5, a4, n3, n2, (const struct sockaddr *) a1, n0); NIPn(5)) \
YV(sockets, sendmsg, n0 = sendmsg(n2, (const struct msghdr *) a1, n0); NIPn(2)) \
YV(sockets, recv, n0 = recv(n3, a2, n1, n0); NIPn(3)) \
YV(sockets, recvfrom, n0 = recvfrom(n5, a4, n3, n2, (struct sockaddr *) a1, (socklen_t *) a0); NIPn(5)) \
YV(sockets, recvmsg, n0 = recvmsg(n2, (struct msghdr *) a1, n0); NIPn(2)) \
XV(sockets, "errno", ERRNO, PUSH errno)
#endif

54
examples/udp.fs Normal file
View File

@ -0,0 +1,54 @@
#! /usr/bin/env ueforth
also sockets
also tasks
also posix
1024 constant max-msg
create msg max-msg allot
-1 value sockfd
variable len max-msg len !
: reader
begin
sockfd msg len 0 0 0 recvfrom
dup 0 >= if
msg swap type cr
else drop then
pause
again
;
' reader 10 10 task reader-task
sockaddr incoming
sockaddr outgoing
: udp ( port -- )
incoming ->port!
AF_INET SOCK_DGRAM 0 socket to sockfd
sockfd non-block throw
sockfd incoming sizeof(sockaddr_in) bind throw
reader-task start-task
stdin non-block throw
;
: say ( port -- )
outgoing ->port!
sockfd tib >in @ + #tib @ >in @ -
0 outgoing sizeof(sockaddr_in) sendto drop
#tib @ >in !
;
: hear begin pause again ;
: help
." USAGE INSTRUCTIONS" cr
." ------------------" cr
." <port> udp ( open UDP connection on port )" cr
." hear ( wait for messages on udp port and print then )" cr
." <port> say <message text> ( send a message to a port )" cr
cr
." Example: 9999 udp hear ( listener )" cr
." Example: 9998 udp 9999 say Can you hear me? ( sender )" cr
;
help quit

View File

@ -23,7 +23,18 @@ z" accept" 3 sysfunc sockaccept
z" poll" 3 sysfunc poll
z" setsockopt" 5 sysfunc setsockopt
z" send" 4 sysfunc send
z" sendto" 6 sysfunc sendto
z" sendmsg" 3 sysfunc sendmsg
z" recv" 4 sysfunc recv
z" recvfrom" 6 sysfunc recvfrom
z" recvmsg" 3 sysfunc recvmsg
1 constant SOCK_STREAM
2 constant SOCK_DGRAM
3 constant SOCK_RAW
2 constant AF_INET
16 constant sizeof(sockaddr_in)
1 constant SOL_SOCKET