amos-pro-bsdsocket-extension/examples/HTTP Server Example.basic

57 lines
1.7 KiB
Plaintext
Raw Normal View History

' This is example code for opening a port on your machine,
' waiting for a client to connect, then printing out the
' first 1024 bytes the server receives from the client.
'
' Copyright 2023 John Bintz
' Licensed under the MIT License
' Visit theindustriousrabbit.com for more information
If Socket Library Open<=0
End
End If
SOCKET=Socket Create Inet Socket
' Ensure our socket does not block, and that we can reuse
' the address we bind to right away if our server is closed.
_=Socket Set Nonblocking(SOCKET,True)
_=Socket Reuse Addr(SOCKET)
' You can bind your socket to any interface on the machine.
' You'd have to get that list of interfaces yourself.
' Using "INADDR_ANY" is the equivalent of binding to 0.0.0.0.
RESULT=Socket Bind(SOCKET To "INADDR_ANY",8000)
_=Socket Listen(SOCKET)
Print "Listening on port 8000"
For I=1 To 100
' Here. we're testing our non-blocking async socket for
' reading. If the socket has been connected to, this request
' will return a value greater than 0. Otherwise, it will
' wait for a half second, then return 0.
RESULT=Socket Wait Async Reading(SOCKET,500)
If RESULT>0
' Accept the connection so we can receive data from it.
_REMOTE_SOCKET=Socket Accept(SOCKET)
' Print out the remote IP address and port.
Print Socket Inet Ntoa$(Socket Get Host(_REMOTE_SOCKET))
Print Socket Get Port(_REMOTE_SOCKET)
' Receive the first 1024 or fewer bytes of data from the
' client and print them out.
Print Socket Recv$(_REMOTE_SOCKET,1024)
' If we exit now, the connection will stay open. Closing the
' library or restarting the program will close all open
' connections.
Exit
End If
Wait Vbl
Next I
Socket Library Close