From aab0b6bf185c419302dda44f9abddf75c57a5898 Mon Sep 17 00:00:00 2001 From: crc Date: Thu, 6 Jun 2019 17:20:03 +0000 Subject: [PATCH] add initial socket examples: client, server FossilOrigin-Name: 706122b5c2fc0fabeb0f694820e56963763a5855f1dcacb65c887151c106482f --- example/socket-client.forth | 38 +++++++++++++++++++++++++++++++++++++ example/socket-server.forth | 31 ++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 example/socket-client.forth create mode 100644 example/socket-server.forth diff --git a/example/socket-client.forth b/example/socket-client.forth new file mode 100644 index 0000000..14586c6 --- /dev/null +++ b/example/socket-client.forth @@ -0,0 +1,38 @@ +This uses the new `socket:` words to download a file via Gopher. + +Open a file to store the data and a socket. + +~~~ +'Output.txt file:open 'File var +socket:create dup n:put nl 'Sock var +~~~ + +Connect to the server. + +~~~ +'forthworks.com '70 socket:configure +@Sock socket:connect drop +~~~ + +Next, send the request. + +~~~ +'/\n\n s:format @Sock socket:send drop-pair +~~~ + +After this, I can just read in the data, writing it to +the file. + +~~~ +[ here #1024 @Sock socket:recv (discard_errno: drop + here [ @File file:write ] s:for-each + dup '%n_bytes_received\n s:format s:put + (check_for_disconnect: n:zero? ] until +~~~ + +And finally, clean up by closing the socket and file. + +~~~ +@Sock socket:close +@File file:close +~~~ diff --git a/example/socket-server.forth b/example/socket-server.forth new file mode 100644 index 0000000..bf4c34f --- /dev/null +++ b/example/socket-server.forth @@ -0,0 +1,31 @@ +Get a socket. + +~~~ +socket:create 'Sock var +~~~ + +Bind to port 9998. + +~~~ +'9998 @Sock socket:bind drop +~~~ + +Prepare to listen for connections. + +~~~ +#3 @Sock socket:listen drop-pair +~~~ + +Serve the user some data. This will repeat 5 times, then end. + +~~~ +#5 [ @Sock socket:accept (discard_error_code: drop ) + 'Hello_from_RETRO\n s:format swap [ socket:send drop-pair ] sip socket:close + ] times +~~~ + +Clean up. + +~~~ +@Sock socket:close +~~~