File: SocketNotifier.C

package info (click to toggle)
witty 3.3.3%2Bdfsg-4.1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 28,228 kB
  • ctags: 26,694
  • sloc: cpp: 147,809; ansic: 77,999; xml: 16,331; sh: 1,303; makefile: 198; java: 86; sql: 14
file content (284 lines) | stat: -rw-r--r-- 8,117 bytes parent folder | download | duplicates (2)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*
 * Copyright (C) 2010 Emweb bvba, Leuven, Belgium.
 *
 * See the LICENSE file for terms of use.
 */
#include <Wt/WApplication>
#include <Wt/WContainerWidget>
#include <Wt/WPushButton>
#include <Wt/WSocketNotifier>
#include <Wt/WText>

#include <iostream>
#include <boost/thread.hpp>

#if WT_WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
typedef int socklen_t;
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#endif

#define HOSTNAME "www.webtoolkit.eu"
#define URL_PATH "/wt/blog/feed/"

/*
 * This is a minimal socket notifier example, which is used to asynchronously
 * read an RSS file and display it in raw format on the browser using server
 * push.
 * Note that when the SocketNotifier signal is emitted, that Wt already
 * conveniently grabbed the update lock for you. You can simply modify
 * the widget tree and use the server push mechanism to push the changes
 * to the browser.
 * The example looks unnecessary complex due to the use of the raw POSIX
 * socket functions. Usually these are wrapped in a more programmer-friendly
 * API.
 */

class RssReader : public Wt::WContainerWidget
{
public:
  RssReader(Wt::WContainerWidget *parent)
    : WContainerWidget(parent),
      state_(CONNECT),
      bytesSent_(0),
      readNotifier_(0),
      writeNotifier_(0)
  {
    new Wt::WText("Click 'Start' to download the Wt homepage RSS feed<br/>"
      "The download will be done asynchronously and this page will update its "
      "contents to inform you about the progress using server push.<br/>",
      this);
    startButton_ = new Wt::WPushButton("Start", this);
    startButton_->clicked().connect(startButton_, &Wt::WPushButton::disable);
    startButton_->clicked().connect(this, &RssReader::startDownload);

    resultText_ = new Wt::WText(this);
    resultText_->setInline(false);
    rssText_ = new Wt::WText(this);
    rssText_->setInline(false);
  }

private:
  int socket_;
  enum {CONNECT, WRITE, READ} state_;
  int bytesSent_;
  Wt::WSocketNotifier *readNotifier_, *writeNotifier_;
  Wt::WPushButton *startButton_;
  Wt::WText *resultText_;
  Wt::WText *rssText_;
  std::stringstream inStream_;

  // Convenience function that updates the status message.
  void addText(const Wt::WString &text)
  {
    resultText_->setText(resultText_->text() + text);
    if (wApp->updatesEnabled())
      wApp->triggerUpdate();

  }

  void startDownload()
  {
    // Enable server push
    wApp->enableUpdates(true);

    rssText_->setText("");
    resultText_->setText("");
    addText("Resolving hostname...");
    startButton_->setText("Busy...");
    /*
     * Name resolving may take a while, so entertain the user
     * already with the updates so far. As this slot is invoked
     * by the browser (caused by the user clicking the 'start'
     * button), we can use processEvents() to send the changes
     * we made to the widget tree up till here back to the browser
     */
    wApp->processEvents();

    struct addrinfo *info;
    if (getaddrinfo(HOSTNAME, "http", 0, &info) == 0) {
      socket_ = ::socket(info->ai_family, info->ai_socktype, info->ai_protocol);
      /*
       * Install notifiers for read and write events. These will end up
       * in a call to select, and activated() will be called whenever
       * select decides that the socket is ready for read or write.
       */
      readNotifier_ = new Wt::WSocketNotifier(socket_,
          Wt::WSocketNotifier::Read, this);
      readNotifier_->setEnabled(false); // Linux fires this on connect, weird
      readNotifier_->activated().connect(this, &RssReader::read);
      writeNotifier_ = new Wt::WSocketNotifier(socket_,
          Wt::WSocketNotifier::Write, this);
      writeNotifier_->activated().connect(this, &RssReader::write);

      // Set sockets to non-blocking
#ifndef WT_WIN32
      int flags = ::fcntl(socket_, F_GETFL, 0);
      flags |= O_NONBLOCK;
      ::fcntl(socket_, F_SETFL, flags);
#else
      u_long enabled = 1;
      ::ioctlsocket(socket_, FIONBIO, &enabled);
#endif
      // Perform a non-blocking connect. POSIX specifies that the socket
      // will be marked as ready for write when the connect call completes.
      int err = ::connect(socket_, info->ai_addr, info->ai_addrlen);
#ifndef WT_WIN32
      int err2 = errno;
#else
      int err2 = GetLastError();
#endif
      freeaddrinfo(info);

      addText(" Done!<br/>Connecting...");
      wApp->processEvents();

      if (err == 0) {
        // connected, proceed immediately to 'writing'
        state_ = WRITE;
        // write() will be invoked automatically by the notifier.
      } else if (err == -1) {
#ifndef WT_WIN32
        if (err2 == EINPROGRESS) {
#else
        if (err2 == WSAEWOULDBLOCK) {
#endif
          state_ = CONNECT;
          // The writeNotifier will be fired when connected
        } else {
          addText(" Problem with connect(). Giving up.<br/>");
          cleanup();
        }
      }
    } else {
      addText("Terminating: could not resolve web service host: " HOSTNAME);
      cleanup();
    }
  }

  void write()
  {
    const char request[] = "GET " URL_PATH " HTTP/1.1\r\n"
      "Host: " HOSTNAME "\r\n"
      "Connection: Close\r\n\r\n";

    switch(state_) {
    case CONNECT:
      {
        int err;
        socklen_t len = sizeof err;
        getsockopt(socket_, SOL_SOCKET, SO_ERROR, (char *)&err, &len);
        if (err != 0) {
          addText(" connect() failed. Giving up.<br/>");
          cleanup();
        } else {
          addText(" Connected!<br/>Writing data");
          state_ = WRITE;
        }
      }
      break;
    case WRITE:
      {
        addText(".");
        // write in bits for demonstration purposes only
        int len = (std::min<int>)(10, (sizeof request) - bytesSent_);
        int retval = ::send(socket_, request + bytesSent_, len, 0);
        if (retval >= 0) {
          bytesSent_ += retval;
          if (bytesSent_ >= (int)(sizeof request)) {
            addText(" Done!<br/>Reading data");
            state_ = READ;
            // We don't need any further notifications that we can
            // keep writing
            writeNotifier_->setEnabled(false);
            readNotifier_->setEnabled(true);
          }
        } else {
#ifndef WT_WIN32
          if (errno != EAGAIN) {
#else
          if (GetLastError() == WSAEWOULDBLOCK) {
#endif
            addText("send() failed. Giving up.<br/>");
            cleanup();
          }
        }
      }
      break;
      case READ:
	break;
    }
  }

  void read()
  {
    addText(".");
    char buf[128];
    int retval = ::recv(socket_, buf, sizeof buf, 0);
    if (retval == 0) {
      // 'orderly shutdown'
      addText(" Done! (Remote end closed connection)<br/>");
      cleanup();
    } else if (retval < 0) {
#ifndef WT_WIN32
      if (errno != EAGAIN) {
#else
      if (GetLastError() == WSAEWOULDBLOCK) {
#endif
        // Euh.. all done?
        addText("recv failed. Giving up.<br/>");
        cleanup();
      }
    } else {
      inStream_.write(buf, retval);
    }
  }

  void cleanup()
  {
    /*
     * It is mandatory not to have notifiers on closed sockets,
     * as select() fails miserably in this case. Disable (or even
     * better, delete) the notifiers before you close the sockets.
     */
    delete readNotifier_;
    delete writeNotifier_;
    readNotifier_ = writeNotifier_ = 0;
#ifdef WT_WIN32
    closesocket(socket_);
#else
    close(socket_);
#endif
    socket_ = 0;
    state_ = CONNECT;
    bytesSent_ = 0;
    startButton_->setText("Again");
    startButton_->enable();
    rssText_->setText("<pre>" +
        escapeText(Wt::WString::fromUTF8(inStream_.str())) + "</pre>");
    addText("Finished!<br/>Run again?<br/>");
    inStream_.str("");
    wApp->enableUpdates(false);
  }
};

Wt::WApplication *createApplication(const Wt::WEnvironment& env)
{
  Wt::WApplication *app = new Wt::WApplication(env);
  new RssReader(app->root());

  return app;
}

int main(int argc, char **argv)
{
  return WRun(argc, argv, &createApplication);
}