TCP Client Forth Programming Swiftforth

Full source code below:

\ import all the libraries / functions we need
\ to build a basic tcp client
library Ws2_32.dll

FUNCTION: WSAStartup ( wVersionRequired lpWSAData – int )
FUNCTION: htons ( hostshort – netshort )
FUNCTION: inet_addr ( *cp – in_addr )
FUNCTION: socket ( af type protocol – SOCKET )
FUNCTION: connect ( s ‘sock len – int )
FUNCTION: send ( s *buf len flags – int )
FUNCTION: recv ( s *buf len flags – int )
FUNCTION: closesocket ( s – int )

\ STEP - 1 startup, ( if you dont do this socket wont create a socket )
\ Version 1.1 (1*256 + 1) = 257 = $0101
: STARTUP ( – flag ) $0101 pad WSAStartup ;
STARTUP

\ STEP - 2 create the struct
CLASS SOCKADDR_IN
HVARIABLE SIN_FAMILY
HVARIABLE SIN_PORT
VARIABLE IN_ADDR
8 BUFFER: SIN_ZERO
END-CLASS

SOCKADDR_IN builds TCPServerAddr

\ STEP - 3 add the ip, port, and AF_INET to the struct
\ www.example.com
AF_INET TCPServerAddr SIN_FAMILY w!
80 htons TCPServerAddr SIN_PORT w!
z" 93.184.216.34" inet_addr TCPServerAddr IN_ADDR !

\ STEP - 4 create the socket , save in var
AF_INET SOCK_STREAM IPPROTO_TCP socket
VALUE TCPClientSocket

\ STEP - 5 connect to server
TCPClientSocket TCPServerAddr this sizeof connect

\ STEP - 6 send a basic GET request to example.com
create clientreply ,z" GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"
TCPClientSocket clientreply zcount 0 send

\ STEP - 7 recieve the data
TCPClientSocket pad 100 0 recv

\ STEP - 8 close the socket (uncomment when finished receiving data)
\ TCPClientSocket closesocket