Bitty HTTP

Development » Dynamic Content

1Dynamic content (chunked output)

This example will show sending dynamic content using chunked transfer encoding.

Chunked encoding is where you do not send the total size of the file you which to send but instead send small chunks of the file and a marker saying you are done.

This is very useful for dynamic content as you do not have to pre build the whole file in RAM before sending it, but instead can send it as you build it.

Files

FileServer.c

We change the file server file removing the graphic stuff we added in the last example and changing the root file to output dynamic content instead of the static content we where using before.

struct FileInfo m_Files[]= { /* Filename, Dynamic, Cookies, Gets, Posts, Callback */ {"/",true,NULL,NULL,NULL,File_Root}, {"/SomeStyle.css",false,NULL,NULL,NULL,File_SomeStyle}, {"/quit.html",true,NULL,NULL,NULL,File_Quit}, };

Here we have changed the root page to be dynamic (true) instead of static (false). Otherwize it stays the same.

const char RootHTML_Start[]= "<!DOCTYPE html>" "<html>" "<head>" "<title>Bitty HTTP - Root</title>" "<link rel='stylesheet' href='/SomeStyle.css'>" "</head>" "<body>" "<div id='top'>Bitty HTTP Example - Root</div>" "<div id='quitbttn'><a href='/quit.html'>QUIT</a></div>" "<div id='content'>"; const char RootHTML_End[]= "</div>" "<div id='bottom'></div>" "</body>" "</html>"; void File_Root(struct WebServer *Web) { static int PageLoads=0; char buff[100]; WS_WriteChunk(Web,RootHTML_Start,sizeof(RootHTML_Start)-1); WS_WriteChunk(Web,"This example shows dynamic content using " "WS_WriteChunk().<br/>",62); sprintf(buff,"You have loaded this page %d times",PageLoads++); WS_WriteChunk(Web,buff,strlen(buff)); WS_WriteChunk(Web,RootHTML_End,sizeof(RootHTML_End)-1); }

The root function has been changed to output the number of times the page has been load since the program was started.

We start by outputing the start of the HTML we want to send from the RootHTML_Start variable. We use the WS_WriteChunk() function instead of the WS_WriteWhole() function.

You can only use WS_WriteChunk() OR WS_WriteWhole() as they change how the HTTP reply is sent and can not be mixed.

We then send a descrition line of text using a const string of 62 bytes in length.

Next we print a line into a string (buff) which includes the number of times this function has been called and we call WS_WriteChunk() passing the buffer. Note that this uses strlen() instead of sizeof(). Sizeof only works on static const data.

Last we send the end of the page from the global variable RootHTML_End.