Skip to content

CPP Input Output Example

gegeturambar edited this page Sep 14, 2016 · 14 revisions

This example is work in progress, do not use it yet (I (Roboticus) needed this, so I tweaked it a little.)

example.cpp

#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <thread>
#include <mutex>

using namespace std;

mutex m;
string *msg;

void in()
{
    while(true)
	{
		for (string line; getline(cin, line);)
		{
		    m.lock();
		    msg = new string("RCVD: ");
		    *msg += line;
		    m.unlock();
		}
	}
}

void out()
{
    while(true)
    {
        m.lock();
        if (msg)
        {
            cout << "You sent me: " << *msg << endl;
            msg = 0;
        }
        m.unlock();
        usleep(1000000);
    }
}

int main() {
    // Disable input/output buffering.
    setbuf(stdout, NULL);
    setbuf(stdin, NULL);

    thread inThread(in);
    thread outThread(out);

    inThread.join();
    outThread.join();

    return 0;
}

Compile with:

g++ -pthread -std=c++0x example.cpp -o example

On MacOSX, Roboticus used:

clang -pthread -std=c++0x example.cpp -o example -lstdc++

Run with:

./websocketd -port=8080 ./example

Interact via the following webpage:

<!DOCTYPE html>
<html>
    <head>
        <title>Simple C++ I/O Example</title>
        <script>
            var ws = new WebSocket('ws://127.0.0.1:8080/');

            ws.onmessage = function(event) {
                document.getElementById('msgBox').innerHTML = event.data;
                document.getElementById('outMsg').value='';
            }
            
            function send()
            {
                ws.send(document.getElementById('outMsg').value);
            }
        </script>
    </head>
    <body>
        <div id='msgBox'>Nothing sent yet!</div>
        <input type="text" id="outMsg">
        <button type="button" onclick="send()">Send</button>
    </body>
</html>
Clone this wiki locally