Skip to content

CPP Input Output Example

mbbackus edited this page Jan 3, 2016 · 14 revisions

example.cpp

#include <stdio.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 = line;
		    m.unlock();
		}
	}
}

void out()
{
    while(true)
    {
        m.lock();
        if(msg == "")
            cout << "You have not sent me a message!" << endl;
        else
            cout << "You sent me: " << msg << endl;
        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

Run with:

./websocketd -port=8080 ./example

Interact via the following webpage:

<!DOCTYPE html>
<html>
    <head>
        <title> </title>
        <script>
            var ws = new WebSocket('ws://192.168.1.147:9090/');

            ws.onmessage = function(event) {
                document.getElementById('msgBox').innerHTML = event.data;
            }
            
            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