Setting the Socket for HTTP
Apart from assigning some memory to the TX, RX, and VAR buffers, the following needs to be done to make a socket work in HTTP mode:
- The protocol must be TCP (sock.protocol = 1 — PL_SOCK_PROTOCOL_TCP).
- The socket must be open for incoming connections (typically, from anybody: sock.inconmode = 3 — PL_SOCK_INCONMODE_ANY_IP_ANY_PORT).
- Reconnects should not be enabled — this is counterproductive for HTTP (sock.reconmode = 0 — PL_SOCK_RECONMODE_0). Reconnects are disabled by default, so just leave it this way.
- The correct listening HTTP port must be set. The default HTTP port on all servers is 80 (sock.httpportlist = "80").
In the previous topic, we explained that your system should reserve several HTTP sockets. Here is a possible initialization example:
dim f as byte
...
'setup for other sockets, etc.
'setup sockets 8-15 for HTTP
for f=8 to 15
sock.num=f
sock.protocol= PL_SOCK_PROTOCOL_TCP
sock.inconmode= PL_SOCK_INCONMODE_ANY_IP_ANY_PORT
sock.httpportlist="80"
next f
....
To make sure that HTTP is working, you can create and add to the project a simple static HTTP file. Call this file index.html — this is a default file that will be called if no specific file is requested by GET or POST. Here is a static file example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD W3 HTML//EN">
<HTML>
<BODY>
HELLO WORLD!<br>
</BODY>
</HTML>
Launch a browser, type the IP address of your device (for example: "http://192.168.1.95"), and you will get the output "HELLO WORLD!"
Don't forget to give your device an IP address. For example, if you are working through a regular wired Ethernet, you should assign an IP address through the net.ip property.
Double-Duty: Non-HTTP and HTTP Processing on the Same Socket
Your HTTP sockets don't have to be exclusively HTTP. You can have them behave differently depending on to which listening port the TCP connection is being made. Here is an example: Suppose the setup of your device needs to be effected in two ways — via TELNET or via HTTP. The standard TELNET port is 23, while the standard HTTP port is 80. Set up your socket like this:
sock.num=f
sock.protocol= PL_SOCK_PROTOCOL_TCP
sock.inconmode= PL_SOCK_INCONMODE_ANY_IP_ANY_PORT
sock.localportlist="23"
sock.httpportlist="80"
....
The socket will now be accepting connections both on port 23 and port 80. When a connection is made to port 23, the socket will work as a regular data socket, as was described in previous sections. When a connection is made to port 80, the socket will automatically switch into the HTTP mode!
There is a property — sock.httpmode — that tells you which mode the socket is in: regular data mode or HTTP. You can even "forcefully" switch any TCP connection into the HTTP mode by setting sock.httpmode = 1 — YES. You cannot, however, switch this connection back to the data mode, it will remain in the HTTP mode until termination.