summaryrefslogtreecommitdiff
path: root/tests/test-Sockets.cc
blob: 0bcfc2ae14267da6ea56d4c038cb8343ef1f1313 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <Main.h>
#include <Socket.h>

using namespace Balau;

class Worker : public Task {
  public:
      Worker(IO<Socket> io, void *);
    virtual const char * getName() const;
    virtual void Do();
    IO<Socket> m_io;
    String m_name;
};

Worker::Worker(IO<Socket> io, void *) : m_io(io) {
    m_name = m_io->getName();
    Printer::log(M_STATUS, "Got connection: %s", m_name.to_charp());
}

const char * Worker::getName() const {
    return m_name.to_charp();
}

void Worker::Do() {
    char x, y;

    int r;
    r = m_io->read(&x, 1);
    TAssert(x == 'x');
    TAssert(r == 1);
    y = 'y';
    r = m_io->write(&y, 1);
    TAssert(r == 1);
}

Listener<Worker> * listener;

class Client : public Task {
  public:
    virtual const char * getName() const { return "Test client"; }
    virtual void Do() {
        sleep(0.1);

        char x, y;
        IO<Socket> s(new Socket());
        bool c = s->connect("localhost", 1234);
        TAssert(c);
        x = 'x';
        int r;
        r = s->write(&x, 1);
        TAssert(r == 1);
        r = s->read(&y, 1);
        TAssert(y == 'y');
        TAssert(r == 1);
        listener->stop();
    }
};

void MainTask::Do() {
    Printer::enable(M_ALL);
    Printer::log(M_STATUS, "Test::Sockets running.");

    Events::TaskEvent evtSvr;
    Events::TaskEvent evtCln;

    listener = TaskMan::registerTask(new Listener<Worker>(1234), &evtSvr);
    TaskMan::registerTask(new Client, &evtCln);

    waitFor(&evtSvr);
    waitFor(&evtCln);

    Printer::log(M_STATUS, "Created %s", listener->getName());
    bool svrDone = false, clnDone = false;
    while (!svrDone || !clnDone) {
        yield();
        if (evtSvr.gotSignal()) {
            evtSvr.ack();
            svrDone = true;
        }
        if (evtCln.gotSignal()) {
            evtCln.ack();
            clnDone = true;
        }
    }

    Printer::log(M_STATUS, "Test::Sockets passed.");
}