Suga koubou / WebSocket_test

http://mbed.org/users/okini3939/notebook/node_websocket/

Dependencies:   EthernetNetIf mbed MbedJSONValue

main.cpp

Committer:
okini3939
Date:
2011-11-02
Revision:
0:236a084b1d6b

File content as of revision 0:236a084b1d6b:

#include "mbed.h"
#include "Websocket.h"
#include "MbedJSONValue.h"
#include "EthernetNetIf.h"

#define BASE_URL "ws://host.domain.name:8080/"

DigitalOut myled(LED1);
Serial pc(USBTX, USBRX);

EthernetNetIf *eth;
Websocket *ws;

int main() {
    int i = 0;
    char buf[100];
    MbedJSONValue json;
    Timer timer;

    eth = new EthernetNetIf();
    EthernetErr ethErr = eth->setup();
    if (ethErr) {
        pc.printf("\r\nERROR %d in setup.\r\n", ethErr);
    }

    ws = new Websocket(BASE_URL "test", eth);

    pc.printf("begin\r\n");

    json["hello"] = "mbed";
    json["num"] = i;

    while(! ws->connect()) {
        pc.printf("cannot connect websocket, retrying...\r\n");
        wait(2);
    }

    timer.start();
    while(1) {
        Net::poll();

        if (timer.read_ms() >= 2000) {
            json["num"] = i ++;
            ws->send((char*)json.serialize().c_str());
            timer.reset();
            myled = myled ? 0 : 1;
       }
        
        if (ws->read(buf)) {
            pc.printf("recv: %s\r\n", buf);
        }

        Net::poll();

        if (! ws->connected()) {
            pc.printf("disconnected\r\n");
            break;
        }
    }
}