Skip to content

CPP Ejemplo de I O

Busindre edited this page Nov 3, 2016 · 3 revisions

C++0x

El ejemplo está todavía en desarrollo por Roboticus, no se recomienda utilizar todavía.

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;
}

Compilar con:

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

En MacOSX, Roboticus usa:

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

Ejecutar de esta manera:

./websocketd -port=8080 --staticdir=. ./example

C++11

#include <iostream>
#include <mutex>
#include <string>
#include <thread>

std::mutex msg_mutex;
std::string msg;

void read()
{
  while (true) {
    std::string sin;
    std::cin >> sin;
    std::lock_guard<std::mutex> lock{msg_mutex};
    msg = sin;
  }
}

void write()
{
  while (true) {
    std::lock_guard<std::mutex> lock{msg_mutex};
    if (msg.length() > 0) {
      std::cout << msg << std::endl;
      msg.clear();
    }
  }
}

int main()
{
  std::thread reader(read);
  std::thread writer(write);

  reader.join();
  writer.join();
  return 0;
}

Compilar con:

clang++ -std=c++11 -pthread -o example example.cpp

Ejecutar con:

./websocketd --port=8080 ./example

Interacción.

Interactuar a través de la siguiente página web:

<!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