Skip to content

C99 Example

Chris Dickens edited this page Feb 4, 2017 · 1 revision

On first connecting this will send the query string to the web socket. From then on it will collect any text entered until it sees a "!" when it will echo back what you sent it. If you send "exit!" it will exit, thereby closing the connection.

talkback.c

// MIT License

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 256

int main(
    int argc,
    char **argv
) {
    // disable buffering - saves needing an explicit fflush( stdout )
    // after printf().
    setbuf( stdout, NULL );
    //
    // Echo the query string (just to show how to get it)
    printf( "Query String: %s\n", getenv( "QUERY_STRING" ) );
    //
    char line[BUFFER_SIZE], c;
    size_t length = 0;
    //
    while( 1 ) {
        // read a char at a time, blocks until each char is available
        c = getchar();
        if( c == '!' ) {
            // if the char is ! then process the line
            line[length] = '\0';
            if( strcmp( line, "exit" ) == 0 ) {
                return 0;
            }
            printf( "you entered: %s\n", line );
            // don't need to flush the buffer as it's disabled above
            length = 0;
        } else if( c >= 32 ) {
            // char is not < 32 nor ! so add to the buffer if not
            //  past the end
            if( length < BUFFER_SIZE ) {
                line[length++] = c;
            }
        }
    }
}
Clone this wiki locally