[
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2014, Jason Kruse <jason@jasonkruse.com>\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n    * Redistributions of source code must retain the above copyright\n      notice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above copyright\n      notice, this list of conditions and the following disclaimer in the\n      documentation and/or other materials provided with the distribution.\n    * The names of its contributors may be used to endorse or promote products\n      derived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL JASON KRUSE BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n*********************************\n\nPlease note this is a C++ wrapper around Andy Green's libwebsockets C library.\nlibwebsockets is licensed under the MIT license.\n\n"
  },
  {
    "path": "README.md",
    "content": "cppWebSockets\n===========\n\nA simple, lightweight c++ WebSockets server library wrapped around the popular libwebsockets c library. \n\n### Usage\n\nCreate a class that extends `WebSocketServer` and implement the following callbacks\n\n```\nvoid onConnect(    int socketID                        ); // New websocket connection\nvoid onMessage(    int socketID, const string& data    ); // Message received from connected client\nvoid onDisconnect( int socketID                        ); // Client disconnect\nvoid   onError(    int socketID, const string& message ); // Networking error\n```\n\nThen simply instantiate your server and call `run()` \n\n```\nMyServer s = MyServer( 8080 ); // MyServer extends WebSocketServer listening on port 8080\ns.run( );\n```\n\nAt any arbitrary time, you can push a message to a client by calling `send( int socketID, string data )`.\n\nIf your server is more complex and needs to monitor its own connections in addition to WebSocket connections, you can manage your own event loop. Instead of calling `s.run( )`, use the `s.wait( )` function.  A good illustration of this is located in [examples/multiPollServer/multiPollServer.cpp](https://github.com/mnisjk/cppWebSockets/blob/master/examples/multiPollServer/multiPollServer.cpp)\n\n### Features\n\n* Implement your own web socket server in less than 50 lines of c++.\n* OpenSSL support\n* WebSocket RFC6455 implementation\n* Abstracts away all c pointers and managing when sockets are writable\n* Push data to any client at any time\n* Key => Value storage for any socket with `setValue( int socketID, const string& name, const string& value );` and `getValue( int socketID, const string& name );`\n\n### Examples\n\nCheck out the [examples](https://github.com/mnisjk/cppWebSockets/blob/master/examples/) directory for fully implemented illustrations.  There is a basic echo and chat server as well as a more complex server that manages multiple `poll( )` loops. They should demonstrate how easy this library is to use and serve as basic scaffolding for your projects.\n\n### Dependencies\n\nThis is built on top of [warmcat](http://warmcat.com/)'s wonderful, lightweight [libwebsocket](http://libwebsockets.org/) c library.  To install:\n\n```\nmnisjk@localdev ~ $ git clone git://git.libwebsockets.org/libwebsockets\nmnisjk@localdev ~ $ cd libwebsockets\nmnisjk@localdev libwebsockets $ cmake .\nmnisjk@localdev libwebsockets $ make\nmnisjk@localdev libwebsockets $ sudo make install\n```\n\n### Compile and run\n\nAll examples have Makefiles, so simply run `make` and then run the example.  When creating your own projects, your compile commands will look like the following:\n\n```\nmnisjk@localdev ~ $ g++ -w -DLOG_TO_STDOUT=1 -omyserver Util.cpp WebSocketServer.cpp myserver.cpp -lwebsockets\nmnisjk@localdev ~ $ ./myserver\n```\n"
  },
  {
    "path": "Util.cpp",
    "content": "/** --------------------------------------------------------------------------\n *  Util.cpp\n *\n *  A few very basic utility functions for WebSocketServer\n *\n *  Author    : Jason Kruse <jason@jasonkruse.com> or @mnisjk\n *  Copyright : 2014\n *  License   : BSD (see LICENSE)\n *  -------------------------------------------------------------------------- \n **/\n\n#include <stdio.h>\n#include \"Util.h\"\n\nusing namespace std;\n\n#define LOG_PREFIX      \"[cppWebSockets] \"\n\nvoid Util::log( const string& message )\n{\n    const string& logMessage = LOG_PREFIX + message;\n    syslog( LOG_WARNING, \"%s\", logMessage.c_str( ) );\n\n#ifdef LOG_TO_STDOUT\n        printf( \"%s\\n\", logMessage.c_str( ) );\n#endif \n}\n\nvoid Util::log( const char* message )\n{\n    log( string( message ) );\n}\n\n"
  },
  {
    "path": "Util.h",
    "content": "/** --------------------------------------------------------------------------\n *  Util.h\n *\n *  A few very basic utility functions for WebSocketServer\n *\n *  Author    : Jason Kruse <jason@jasonkruse.com> or @mnisjk\n *  Copyright : 2014\n *  License   : BSD (see LICENSE)\n *  -------------------------------------------------------------------------- \n **/\n\n#ifndef _UTIL_H\n#define _UTIL_H\n\n#include <string>\n#include <syslog.h>\n#include <iostream>\n#include <sstream>\n\nusing namespace std;\n\n/////////////////////////////////////////////////////////////////////////////\n/////////////////////////////////////////////////////////////////////////////\n/// Util\n/// ---------\n\nclass Util\n{\npublic:\n    static void   log( const string& message );\n    static void   log( const char* message );\n    template<typename T>\n    static inline string toString(T t) { stringstream s; s << t; return s.str(); }\n};\n\n// Util.h\n#endif\n\n"
  },
  {
    "path": "WebSocketServer.cpp",
    "content": "/** --------------------------------------------------------------------------\n *  WebSocketServer.cpp\n *\n *  Base class that WebSocket implementations must inherit from.  Handles the\n *  client connections and calls the child class callbacks for connection\n *  events like onConnect, onMessage, and onDisconnect.\n *\n *  Author    : Jason Kruse <jason@jasonkruse.com> or @mnisjk\n *  Copyright : 2014\n *  License   : BSD (see LICENSE)\n *  --------------------------------------------------------------------------\n **/\n\n#include <stdlib.h>\n#include <string>\n#include <cstring>\n#include <sys/time.h>\n#include <fcntl.h>\n#include \"libwebsockets.h\"\n#include \"Util.h\"\n#include \"WebSocketServer.h\"\n\nusing namespace std;\n\n// 0 for unlimited\n#define MAX_BUFFER_SIZE 0\n\n// Nasty hack because certain callbacks are statically defined\nWebSocketServer *self;\n\nstatic int callback_main(   struct lws *wsi,\n                            enum lws_callback_reasons reason,\n                            void *user,\n                            void *in,\n                            size_t len )\n{\n    int fd;\n    unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING + 512 + LWS_SEND_BUFFER_POST_PADDING];\n    unsigned char *p = &buf[LWS_SEND_BUFFER_PRE_PADDING];\n\n    switch( reason ) {\n        case LWS_CALLBACK_ESTABLISHED:\n            self->onConnectWrapper( lws_get_socket_fd( wsi ) );\n            lws_callback_on_writable( wsi );\n            break;\n\n        case LWS_CALLBACK_SERVER_WRITEABLE:\n            fd = lws_get_socket_fd( wsi );\n            while( !self->connections[fd]->buffer.empty( ) )\n            {\n                const char * message = self->connections[fd]->buffer.front( );\n                int msgLen = strlen(message);\n                int charsSent = lws_write( wsi, (unsigned char *)message, msgLen, LWS_WRITE_TEXT );\n                if( charsSent < msgLen )\n                    self->onErrorWrapper( fd, string( \"Error writing to socket\" ) );\n                else\n                    // Only pop the message if it was sent successfully.\n                    self->connections[fd]->buffer.pop_front( );\n            }\n            lws_callback_on_writable( wsi );\n            break;\n\n        case LWS_CALLBACK_RECEIVE:\n            self->onMessage( lws_get_socket_fd( wsi ), string( (const char *)in, len ) );\n            break;\n\n        case LWS_CALLBACK_CLOSED:\n            self->onDisconnectWrapper( lws_get_socket_fd( wsi ) );\n            break;\n\n        default:\n            break;\n    }\n    return 0;\n}\n\nstatic struct lws_protocols protocols[] = {\n    {\n        \"/\",\n        callback_main,\n        0, // user data struct not used\n        MAX_BUFFER_SIZE,\n    },{ NULL, NULL, 0, 0 } // terminator\n};\n\nWebSocketServer::WebSocketServer( int port, const string certPath, const string& keyPath )\n{\n    this->_port     = port;\n    this->_certPath = certPath;\n    this->_keyPath  = keyPath;\n\n    lws_set_log_level( 0, lwsl_emit_syslog ); // We'll do our own logging, thank you.\n    struct lws_context_creation_info info;\n    memset( &info, 0, sizeof info );\n    info.port = this->_port;\n    info.iface = NULL;\n    info.protocols = protocols;\n#ifndef LWS_NO_EXTENSIONS\n    info.extensions = lws_get_internal_extensions( );\n#endif\n\n    if( !this->_certPath.empty( ) && !this->_keyPath.empty( ) )\n    {\n        Util::log( \"Using SSL certPath=\" + this->_certPath + \". keyPath=\" + this->_keyPath + \".\" );\n        info.ssl_cert_filepath        = this->_certPath.c_str( );\n        info.ssl_private_key_filepath = this->_keyPath.c_str( );\n    }\n    else\n    {\n        Util::log( \"Not using SSL\" );\n        info.ssl_cert_filepath        = NULL;\n        info.ssl_private_key_filepath = NULL;\n    }\n    info.gid = -1;\n    info.uid = -1;\n    info.options = 0;\n\n    // keep alive\n    info.ka_time = 60; // 60 seconds until connection is suspicious\n    info.ka_probes = 10; // 10 probes after ^ time\n    info.ka_interval = 10; // 10s interval for sending probes\n    this->_context = lws_create_context( &info );\n    if( !this->_context )\n        throw \"libwebsocket init failed\";\n    Util::log( \"Server started on port \" + Util::toString( this->_port ) );\n\n    // Some of the libwebsocket stuff is define statically outside the class. This\n    // allows us to call instance variables from the outside.  Unfortunately this\n    // means some attributes must be public that otherwise would be private.\n    self = this;\n}\n\nWebSocketServer::~WebSocketServer( )\n{\n    // Free up some memory\n    for( map<int,Connection*>::const_iterator it = this->connections.begin( ); it != this->connections.end( ); ++it )\n    {\n        Connection* c = it->second;\n        this->connections.erase( it->first );\n        delete c;\n    }\n}\n\nvoid WebSocketServer::onConnectWrapper( int socketID )\n{\n    Connection* c = new Connection;\n    c->createTime = time( 0 );\n    this->connections[ socketID ] = c;\n    this->onConnect( socketID );\n}\n\nvoid WebSocketServer::onDisconnectWrapper( int socketID )\n{\n    this->onDisconnect( socketID );\n    this->_removeConnection( socketID );\n}\n\nvoid WebSocketServer::onErrorWrapper( int socketID, const string& message )\n{\n    Util::log( \"Error: \" + message + \" on socketID '\" + Util::toString( socketID ) + \"'\" );\n    this->onError( socketID, message );\n    this->_removeConnection( socketID );\n}\n\nvoid WebSocketServer::send( int socketID, string data )\n{\n    // Push this onto the buffer. It will be written out when the socket is writable.\n    this->connections[socketID]->buffer.push_back( data.c_str() );\n}\n\nvoid WebSocketServer::broadcast(string data )\n{\n    for( map<int,Connection*>::const_iterator it = this->connections.begin( ); it != this->connections.end( ); ++it )\n        this->send( it->first, data );\n}\n\nvoid WebSocketServer::setValue( int socketID, const string& name, const string& value )\n{\n    this->connections[socketID]->keyValueMap[name] = value;\n}\n\nstring WebSocketServer::getValue( int socketID, const string& name )\n{\n    return this->connections[socketID]->keyValueMap[name];\n}\nint WebSocketServer::getNumberOfConnections( )\n{\n    return this->connections.size( );\n}\n\nvoid WebSocketServer::run( uint64_t timeout )\n{\n    while( 1 )\n    {\n        this->wait( timeout );\n    }\n}\n\nvoid WebSocketServer::wait( uint64_t timeout )\n{\n    if( lws_service( this->_context, timeout ) < 0 )\n        throw \"Error polling for socket activity.\";\n}\n\nvoid WebSocketServer::_removeConnection( int socketID )\n{\n    Connection* c = this->connections[ socketID ];\n    this->connections.erase( socketID );\n    delete c;\n}\n"
  },
  {
    "path": "WebSocketServer.h",
    "content": "/** --------------------------------------------------------------------------\n *  WebSocketServer.h\n *\n *  Base class that WebSocket implementations must inherit from.  Handles the\n *  client connections and calls the child class callbacks for connection\n *  events like onConnect, onMessage, and onDisconnect.\n *\n *  Author    : Jason Kruse <jason@jasonkruse.com> or @mnisjk\n *  Copyright : 2014\n *  License   : BSD (see LICENSE)\n *  --------------------------------------------------------------------------\n **/\n\n#ifndef _WEBSOCKETSERVER_H\n#define _WEBSOCKETSERVER_H\n#include <stdint.h>\n#include <map>\n#include <string>\n#include <list>\n#include <stdio.h>\n#include <ctime>\n#include <sys/time.h>\n#include <iostream>\n#include <sstream>\n#include \"libwebsockets.h\"\n\nusing namespace std;\n\n/////////////////////////////////////////////////////////////////////////////\n/////////////////////////////////////////////////////////////////////////////\n/// WebSocketServer\n/// ---------\nclass WebSocketServer\n{\npublic:\n    // Represents a client connection\n    struct Connection\n    {\n        list<const char*>       buffer;     // Ordered list of pending messages to flush out when socket is writable\n        map<string,string> keyValueMap;\n        time_t             createTime;\n    };\n\n    // Manages connections. Unfortunately this is public because static callback for\n    // libwebsockets is defined outside the instance and needs access to it.\n    map<int,Connection*> connections;\n\n    // Constructor / Destructor\n    WebSocketServer( int port, const string certPath = \"\", const string& keyPath = \"\" );\n    ~WebSocketServer( );\n\n    void run(       uint64_t timeout = 50     );\n    void wait(      uint64_t timeout = 50     );\n    void send(      int socketID, string data );\n    void broadcast( string data               );\n\n    // Key => value storage for each connection\n    string getValue( int socketID, const string& name );\n    void   setValue( int socketID, const string& name, const string& value );\n    int    getNumberOfConnections( );\n\n    // Overridden by children\n    virtual void onConnect(    int socketID                        ) = 0;\n    virtual void onMessage(    int socketID, const string& data    ) = 0;\n    virtual void onDisconnect( int socketID                        ) = 0;\n    virtual void   onError(    int socketID, const string& message ) = 0;\n\n\n    // Wrappers, so we can take care of some maintenance\n    void onConnectWrapper(    int socketID );\n    void onDisconnectWrapper( int socketID );\n    void onErrorWrapper( int socketID, const string& message );\n\nprotected:\n    // Nothing, yet.\n\nprivate:\n    int                  _port;\n    string               _keyPath;\n    string               _certPath;\n    struct lws_context  *_context;\n\n    void _removeConnection( int socketID );\n};\n\n// WebSocketServer.h\n#endif\n"
  },
  {
    "path": "examples/chatServer/Makefile",
    "content": "hellomake:\n\tg++ -w -DLOG_TO_STDOUT=1 -ochatserver ../../Util.cpp ../../WebSocketServer.cpp chatServer.cpp -lwebsockets\n"
  },
  {
    "path": "examples/chatServer/chatServer.cpp",
    "content": "/** --------------------------------------------------------------------------\n *  chatServer.cpp\n *\n *  A basic example of how to implement a WebSocketServer.  Creats a WS server\n *  bound to port 8080 for basic chatting.  It listens for connections and\n *  assigns them a random handle based on their socket FD.  Whenever a message\n *  is received on the server, it is sent out to all connected clients.\n *  received, it echos the same message back to the client.\n *\n *  Author    : Jason Kruse <jason@jasonkruse.com> or @mnisjk\n *  Copyright : 2014\n *  License   : BSD (see LICENSE)\n *  -------------------------------------------------------------------------- \n **/\n\n// Log to stdout for easy debugging.\n#define LOG_TO_STDOUT 1\n\n#include \"../../Util.h\"\n#include \"../../WebSocketServer.h\"\n\nusing namespace std;\n\n// For any real project this should be defined separately in a header file\nclass ChatServer : public WebSocketServer\n{\npublic: \n    ChatServer( int port );\n    ~ChatServer( );\n    virtual void onConnect(    int socketID                        );\n    virtual void onMessage(    int socketID, const string& data    );\n    virtual void onDisconnect( int socketID                        );\n    virtual void   onError(    int socketID, const string& message );\n};\n\nint main( int argc, char **argv )\n{\n    ChatServer cs = ChatServer( 8080 );\n    cs.run( );\n}\n\nChatServer::ChatServer( int port ) : WebSocketServer( port )\n{\n}\n\nChatServer::~ChatServer( )\n{\n}\n\n\nvoid ChatServer::onConnect( int socketID )\n{\n    // Give this connection a random user ID\n    const string& handle = \"User #\" + Util::toString( socketID );\n    Util::log( \"New connection: \" + handle );\n    \n    // Associate this handle with the connection\n    this->setValue( socketID, \"handle\", handle );\n\n    // Let everyone know the new user has connected\n    this->broadcast( handle + \" has connected.\" );\n}\n\nvoid ChatServer::onMessage( int socketID, const string& data )\n{\n    // Send the received message to all connected clients in the form of 'User XX: message...'\n    Util::log( \"Received: \" + data );\n    const string& message = this->getValue( socketID, \"handle\" ) + \": \" + data;\n\n    this->broadcast( message );\n}\n\nvoid ChatServer::onDisconnect( int socketID )\n{\n    const string& handle = this->getValue( socketID, \"handle\" );\n    Util::log( \"Disconnected: \" + handle );\n    \n    // Let everyone know the user has disconnected\n    const string& message = handle + \" has disconnected.\";\n    for( map<int,Connection*>::const_iterator it = this->connections.begin( ); it != this->connections.end( ); ++it )\n        if( it->first != socketID )\n            // The disconnected connection gets deleted after this function runs, so don't try to send to it\n            // (It's still around in case the implementing class wants to perform any clean up actions)\n            this->send( it->first, message );\n}\n\nvoid ChatServer::onError( int socketID, const string& message )\n{\n    Util::log( \"Error: \" + message );\n}\n\n"
  },
  {
    "path": "examples/chatServer/index.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>cppWebSockets chat server example</title>\n        <meta name=\"author\"    value=\"jason@jasonkruse.com\" />\n        <meta name=\"licsense\"  value=\"BSD\" />\n        <meta name=\"robots\"    value=\"none\" />\n        <style type=\"text/css\">\n            * { margin: 5px; }\n            textarea {\n                display: block;\n                width:   80%;\n                margin:  0;\n                height:  200px;\n            }\n            \n        </style>\n    </head>\n    <body>\n        <h3>Basic chat server</h3>\n        <div>\n            <p>\n                This is a super basic example of a chat server using lwebsockets++. This also\n                shows how to use the key => value storage to associate data with a connection.    \n            </p>\n            <ul><br />\n                <li>Compile and run the server in examples/chatServer.</li>\n                <li>Open this page in multiple tabs.</li>\n                <li>Start chatting with yourself</li>\n            </ul>\n            <p><br />\n                <i>Note: </i>\n                There is no flash fallback, so make sure you have a modern browser with\n                WebSocket support.\n            </p>\n        </div>\n        <fieldset>\n            <legend>Demo</legend>\n            <textarea id=\"output\" readonly></textarea>\n            <textarea id=\"input\" placeholder=\"Enter a message\"></textarea>\n            <input type=\"button\" name=\"inpuBtn\" id=\"inputBtn\" value=\"Send\" />\n            <div><u>Server responses</u></div>\n        </fieldset>\n        \n        <script type=\"text/javascript\">\n            // Putting the js here after the dom is available in the browser because not using a framework\n            var PORT = 8080;\n            var ws = new WebSocket(\"ws://localhost:\" + PORT );\n            var input    = document.getElementById(\"input\");\n            var inputBtn = document.getElementById(\"inputBtn\");\n            var output   = document.getElementById(\"output\");\n\n            inputBtn.onclick = function( evt ){\n                sendMessage();\n            };\n\n            input.onkeypress = function( evt ){\n                var code = evt.keyCode ? evt.keyCode : evt.which;\n                if( code == 13 ){\n                    evt.preventDefault();\n                    sendMessage();\n                }\n            };\n\n            ws.onmessage = function( evt ){\n                addMessage( evt.data );\n            };\n\n            ws.onerror = function( evt ) { \n                addMessage( 'WebSocket error :(' );\n            };\n\n            ws.onopen = function( evt ) { \n                // Unused\n            };\n\n            ws.onclose = function( evt ) { \n                addMessage( 'You disconnected' );\n            };\n\n            function sendMessage( ){\n                ws.send(input.value);\n                input.value = '';\n            }\n\n            function addMessage( msg ){\n                output.value += msg + \"\\n\"; \n                output.scrollTop = output.scrollHeight;\n            }\n        </script>\n    </body>\n</html>\n\n"
  },
  {
    "path": "examples/echoServer/Makefile",
    "content": "hellomake:\n\tg++ -w -DLOG_TO_STDOUT=1 -oechoserver ../../Util.cpp ../../WebSocketServer.cpp echoServer.cpp -lwebsockets\n"
  },
  {
    "path": "examples/echoServer/echoServer.cpp",
    "content": "/** --------------------------------------------------------------------------\n *  echoServer.cpp\n *\n *  A basic example of how to implement a WebSocketServer.  Creats a WS server\n *  bound to port 8080.  It listens for connections, and when a message is \n *  received, it echos the same message back to the client.\n *\n *  Author    : Jason Kruse <jason@jasonkruse.com> or @mnisjk\n *  Copyright : 2014\n *  License   : BSD (see LICENSE)\n *  -------------------------------------------------------------------------- \n **/\n\n// Log to stdout for easy debugging.\n#define LOG_TO_STDOUT 1\n\n#include \"../../Util.h\"\n#include \"../../WebSocketServer.h\"\n\nusing namespace std;\n\n// For any real project this should be defined separately in a header file\nclass EchoServer : public WebSocketServer\n{\npublic: \n    EchoServer( int port );\n    ~EchoServer( );\n    virtual void onConnect(    int socketID                        );\n    virtual void onMessage(    int socketID, const string& data    );\n    virtual void onDisconnect( int socketID                        );\n    virtual void   onError(    int socketID, const string& message );\n};\n\nint main( int argc, char **argv )\n{\n    EchoServer es = EchoServer( 8080 );\n    es.run( );\n}\n\nEchoServer::EchoServer( int port ) : WebSocketServer( port )\n{\n}\n\nEchoServer::~EchoServer( )\n{\n}\n\n\nvoid EchoServer::onConnect( int socketID )\n{\n    Util::log( \"New connection\" );\n}\n\nvoid EchoServer::onMessage( int socketID, const string& data )\n{\n    // Reply back with the same message\n    Util::log( \"Received: \" + data );\n    this->send( socketID, data );\n}\n\nvoid EchoServer::onDisconnect( int socketID )\n{\n    Util::log( \"Disconnect\" );\n}\n\nvoid EchoServer::onError( int socketID, const string& message )\n{\n    Util::log( \"Error: \" + message );\n}\n\n\n"
  },
  {
    "path": "examples/echoServer/index.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>cppWebSockets echo example</title>\n        <meta name=\"author\"    value=\"jason@jasonkruse.com\" />\n        <meta name=\"licsense\"  value=\"BSD\" />\n        <meta name=\"robots\"    value=\"none\" />\n        <style type=\"text/css\">\n            * { margin: 5px; }\n        </style>\n    </head>\n    <body>\n        <h3>Send a message to the server</h3>\n        <div>\n            <p>This is a super basic example of how to connect to the websocket server.</p>\n            <ul><br />\n                <li>Compile and run the server in examples/echoServer.</li>\n                <li>\n                    Enter a message in the text box below; it will be sent to the server which \n                    will reply back with the same message.\n                </li>\n            </ul>\n            <p><br />\n                <i>Note: </i>\n                There is no flash fallback, so make sure you have a modern browser with\n                WebSocket support.\n            </p>\n        </div>\n        <fieldset>\n            <legend>Demo</legend>\n            <input type=\"text\" name=\"input\" id=\"input\" />\n            <input type=\"button\" name=\"inpuBtn\" id=\"inputBtn\" value=\"Send\" />\n            <div><u>Server responses</u></div>\n            <div id=\"output\"></div>\n        </fieldset>\n        \n        <script type=\"text/javascript\">\n            // Putting the js here after the dom is available in the browser because not using a framework\n            var PORT = 8080;\n            var ws = new WebSocket(\"ws://localhost:\" + PORT );\n            var input    = document.getElementById(\"input\");\n            var inputBtn = document.getElementById(\"inputBtn\");\n            var output   = document.getElementById(\"output\");\n\n            inputBtn.onclick = function( evt ){\n                sendMessage();\n            };\n\n            input.onkeypress = function( evt ){\n                var code = evt.keyCode ? evt.keyCode : evt.which;\n                if( code == 13 )\n                    sendMessage();\n            };\n\n            ws.onmessage = function( evt ){\n                addMessage( evt.data );\n            };\n\n            ws.onerror = function( evt ) { \n                addMessage( '<i>WebSocket error :(</i>' );\n            };\n\n            ws.onopen = function( evt ) { \n                addMessage( '<i>Connected</i>' );\n            };\n\n            ws.onclose = function( evt ) { \n                addMessage( '<i>Disconnected</i>' );\n            };\n\n            function sendMessage( ){\n                ws.send(input.value);\n                input.value = '';\n            }\n\n            function addMessage( msg ){\n                output.innerHTML += msg + '<br />'; \n            }\n        </script>\n    </body>\n</html>\n\n"
  },
  {
    "path": "examples/multiPollServer/Makefile",
    "content": "hellomake:\n\tg++ -w -omultipollserver ../../Util.cpp ../../WebSocketServer.cpp multiPollServer.cpp -lwebsockets\n"
  },
  {
    "path": "examples/multiPollServer/index.html",
    "content": "<!DOCTYPE html>\n<html>\n    <head>\n        <title>cppWebSockets multipoll example</title>\n        <meta name=\"author\"    value=\"jason@jasonkruse.com\" />\n        <meta name=\"licsense\"  value=\"BSD\" />\n        <meta name=\"robots\"    value=\"none\" />\n        <style type=\"text/css\">\n            * { margin: 5px; }\n        </style>\n    </head>\n    <body>\n        <h3>Multi Poll server</h3>\n        <div>\n            <p>\n                A basic example of how to implement a WebSocketServer <i>and</i> listen to other\n               fds.\n            </p><br />\n            <p>\n               This is useful when your server needs to handle connections from \n               WebSocket clients and other TCP connections at the same time.\n            </p>\n            <ul><br />\n                <li>Compile and run the server in examples/multiPollServer.</li>\n                <li>\n                    Enter messages into standard input and they will be sent out to\n                    all connected clients.\n                </li>\n            </ul>\n            <p><br />\n                <i>Note: </i>\n                There is no flash fallback, so make sure you have a modern browser with\n                WebSocket support.\n            </p>\n        </div>\n        <fieldset>\n            <legend>Demo</legend>\n            <div><u>Server messages</u></div>\n            <div id=\"output\"></div>\n        </fieldset>\n        \n        <script type=\"text/javascript\">\n            // Putting the js here after the dom is available in the browser because not using a framework\n            var PORT = 8080;\n            var ws = new WebSocket(\"ws://localhost:\" + PORT );\n            var output   = document.getElementById(\"output\");\n\n            ws.onmessage = function( evt ){\n                addMessage( evt.data );\n            };\n\n            ws.onerror = function( evt ) { \n                addMessage( '<i>WebSocket error :(</i>' );\n            };\n\n            ws.onopen = function( evt ) { \n                addMessage( '<i>Connected</i>' );\n            };\n\n            ws.onclose = function( evt ) { \n                addMessage( '<i>Disconnected</i>' );\n            };\n\n            function addMessage( msg ){\n                output.innerHTML += msg + '<br />'; \n            }\n        </script>\n    </body>\n</html>\n\n"
  },
  {
    "path": "examples/multiPollServer/multiPollServer.cpp",
    "content": "/** --------------------------------------------------------------------------\n *  multiPollServer.cpp\n *\n *  A basic example of how to implement a WebSocketServer *AND* listen to other\n *  fds. This is useful when your server needs to handle connections from \n *  WebSocket clients and other TCP connections at the same time.\n *\n *  It also demonstrates how to send to an arbitrary WebSocket connection at\n *  any time.\n *\n *  This program listens for input on stdin and WebSockets on port 8080 \n *  simultaneously. When new data is available on stdin (line buffered),\n *  it sends that string out to all connected WebSocket clients.\n *\n *  Author    : Jason Kruse <jason@jasonkruse.com> or @mnisjk\n *  Copyright : 2014\n *  License   : BSD (see LICENSE)\n *  -------------------------------------------------------------------------- \n **/\n\n#include <string>\n#include <fcntl.h>\n#include \"../../Util.h\"\n#include \"../../WebSocketServer.h\"\n\n#define TIMEOUT    50\n#define PROMPT     \"message> \"\n\nusing namespace std;\n\n// For any real project this should be defined separately in a header file\nclass MultiPollServer : public WebSocketServer\n{\npublic: \n    MultiPollServer( int port );\n    ~MultiPollServer( );\n    virtual void onConnect(    int socketID                        );\n    virtual void onMessage(    int socketID, const string& data    );\n    virtual void onDisconnect( int socketID                        );\n    virtual void   onError(    int socketID, const string& message );\n};\n\n\nvoid showPrompt( )\n{\n    cout << PROMPT;\n    fflush( stdout );\n}\n\nint main( int argc, char **argv )\n{\n    // Set up the stdin polling\n    int p;\n    char buf[1024];\n    struct pollfd pfds[1];\n    pfds[0].fd = 0;\n    pfds[0].events = POLLIN;\n    \n    // Start the WebSocket server\n    MultiPollServer s = MultiPollServer( 8080 );\n    \n    cout << \"Type a message followed by enter to send to all connected clients.\" << endl << endl; \n    showPrompt( );\n    while( 1 )\n    {\n        // Handle websocket stuff\n        s.wait( TIMEOUT );\n\n        // Handle stdin\n        p = poll( pfds, 1, TIMEOUT );\n        if( p > 0 && pfds[0].revents & POLLIN )\n        {\n            int len = read( 0, buf, 1024 );\n            if( !len )\n                return 0;\n            buf[len] = 0; // make sure the c-string terminator is where we want it to be since this buf is re-used.\n            string input = string( buf );\n            input.resize( input.size( ) - 1 ); // Remove the trailing \\n\n            \n            // Send it out to WS clients.\n            Util::log( \"Sending '\" + input  + \"' to \" + Util::toString( s.getNumberOfConnections( ) ) + \" client(s).\" );\n            s.broadcast( input ); \n            \n            // Diplay the prompt.\n            showPrompt( );\n        }\n    }\n}\n\nMultiPollServer::MultiPollServer( int port ) : WebSocketServer( port )\n{\n}\n\nMultiPollServer::~MultiPollServer( )\n{\n}\n\n\nvoid MultiPollServer::onConnect( int socketID )\n{\n    Util::log( \"New connection\" );\n}\n\nvoid MultiPollServer::onMessage( int socketID, const string& data )\n{\n    // Should never get hit.\n}\n\nvoid MultiPollServer::onDisconnect( int socketID )\n{\n    Util::log( \"Disconnect\" );\n}\n\nvoid MultiPollServer::onError( int socketID, const string& message )\n{\n    Util::log( \"Error: \" + message );\n}\n\n\n"
  }
]