summaryrefslogtreecommitdiff
path: root/examples/network/socket-server.cc
blob: 360c90bdbbe6b02432ed6177462af4fd36fd9ac0 (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
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#include <iostream>
#include <giomm.h>
#include <glibmm.h>

namespace
{

Glib::RefPtr<Glib::MainLoop> loop;

int port = 7777;
bool verbose = false;
bool dont_reuse_address = false;
bool non_blocking = false;
bool use_udp = false;
bool use_source = false;
bool use_ipv6 = false;
int cancel_timeout = 0;

class ServerOptionGroup : public Glib::OptionGroup
{
public:
  ServerOptionGroup()
  : Glib::OptionGroup("server_group", "", "")
  {
    Glib::OptionEntry entry;
    entry.set_long_name("port");
    entry.set_short_name('p');
    entry.set_description("Local port to bind to, default: 7777");
    add_entry(entry, port);

    entry.set_long_name("cancel");
    entry.set_short_name('c');
    entry.set_description("Cancel any op after the specified amount of seconds");
    add_entry(entry, cancel_timeout);

    entry.set_long_name("udp");
    entry.set_short_name('u');
    entry.set_description("Use UDP instead of TCP");
    add_entry(entry, use_udp);

    entry.set_long_name("verbose");
    entry.set_short_name('v');
    entry.set_description("Be verbose");
    add_entry(entry, verbose);

    entry.set_long_name("no-reuse");
    entry.set_short_name('\0');
    entry.set_description("Don't SOADDRREUSE");
    add_entry(entry, dont_reuse_address);

    entry.set_long_name("non-blocking");
    entry.set_short_name('n');
    entry.set_description("Enable non-blocking I/O");
    add_entry(entry, non_blocking);

    entry.set_long_name("use-source");
    entry.set_short_name('s');
    entry.set_description("Use Gio::SocketSource to wait for non-blocking I/O");
    add_entry(entry, use_source);

    entry.set_long_name("use-ipv6");
    entry.set_short_name('6');
    entry.set_description("Use IPv6 address family");
    add_entry(entry, use_ipv6);
  }
};  

Glib::ustring
socket_address_to_string (const Glib::RefPtr<Gio::SocketAddress>& address)
{
  auto isockaddr =
      Glib::RefPtr<Gio::InetSocketAddress>::cast_dynamic (address);
  if (!isockaddr)
      return Glib::ustring ();

  auto inet_address = isockaddr->get_address ();
  auto str = inet_address->to_string ();
  auto port = isockaddr->get_port ();
  auto res = Glib::ustring::compose ("%1:%2", str, port);
  return res;
}

static bool
source_ready(Glib::IOCondition /*condition*/)
{
  loop->quit ();
  return false;
}

static void
ensure_condition (const Glib::RefPtr<Gio::Socket>& socket,
                  const Glib::ustring& where,
                  const Glib::RefPtr<Gio::Cancellable>& cancellable,
                  Glib::IOCondition condition)
{
    if (!non_blocking)
        return;

    if (use_source)
    {
      Gio::signal_socket().connect(sigc::ptr_fun(&source_ready), socket, condition);
      loop->run();
    }
    else
    {
        try {
            socket->condition_wait (condition, cancellable);
        } catch (const Gio::Error& error)
        {
            std::cerr << Glib::ustring::compose("condition wait error for %1: %2\n",
                        where, error.what ());
            exit (1);
        }
    }
}

static void
cancel_thread (Glib::RefPtr<Gio::Cancellable> cancellable)
{
    g_usleep (1000*1000*cancel_timeout);
    std::cout << "Cancelling\n";
    cancellable->cancel ();
}

} // end anonymous namespace

int
main (int argc,
      char *argv[])
{
    Glib::RefPtr<Gio::Socket> socket, new_socket, recv_socket;
    Glib::RefPtr<Gio::SocketAddress> address;
    Glib::RefPtr<Gio::Cancellable> cancellable;

    Gio::init ();

    Glib::OptionContext option_context(" - Test Gio::Socket server stuff");
    ServerOptionGroup option_group;
    option_context.set_main_group(option_group);
    try
    {
      option_context.parse(argc, argv);
    }
    catch (const Glib::Error& error)
    {
      std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error.what());
      return 1;
    }

    if (cancel_timeout)
    {
        cancellable = Gio::Cancellable::create ();
        Glib::Threads::Thread::create (sigc::bind (sigc::ptr_fun (cancel_thread), cancellable));
    }

    loop = Glib::MainLoop::create ();

    auto socket_type = use_udp ? Gio::SOCKET_TYPE_DATAGRAM : Gio::SOCKET_TYPE_STREAM;
    auto socket_family = use_ipv6 ? Gio::SOCKET_FAMILY_IPV6 : Gio::SOCKET_FAMILY_IPV4;

    try {
        socket = Gio::Socket::create (socket_family, socket_type, Gio::SOCKET_PROTOCOL_DEFAULT);
    } catch (const Gio::Error& error)
    {
        std::cerr << Glib::ustring::compose ("%1: %2\n", argv[0], error.what ());
        return 1;
    }

    if (non_blocking)
        socket->set_blocking (false);

    auto src_address = Gio::InetSocketAddress::create (Gio::InetAddress::create_any (socket_family), port);
    try {
        socket->bind (src_address, !dont_reuse_address);
    } catch (const Gio::Error& error) {
        std::cerr << Glib::ustring::compose ("Can't bind socket: %1\n",
                                             error.what ());
        return 1;
    }

    if (!use_udp)
    {
        try {
            socket->listen ();
        } catch (const Gio::Error& error)
        {
            std::cerr << Glib::ustring::compose ("Can't listen on socket: %1\n",
                                                 error.what ());
            return 1;
        }

        std::cout << Glib::ustring::compose ("listening on port %1...\n", port);

        ensure_condition (socket, "accept", cancellable, Glib::IO_IN);
        try {
            new_socket = socket->accept (cancellable);
        } catch (const Gio::Error& error)
        {
            std::cerr << Glib::ustring::compose ("Error accepting socket: %1\n",
                                                 error.what ());
            return 1;
        }

        if (non_blocking)
            new_socket->set_blocking (false);

        try {
        address = new_socket->get_remote_address ();
        } catch (const Gio::Error& error)
        {
            std::cerr << Glib::ustring::compose ("Error getting remote address: %1\n",
                                                 error.what ());
            return 1;
        }

        std::cout << Glib::ustring::compose ("got a new connection from %1\n",
                                             socket_address_to_string (address));

        recv_socket = new_socket;
    }
    else
    {
        recv_socket = socket;
    }


    while (true)
    {
        gchar buffer[4096] = { };
        gssize size;

        ensure_condition (recv_socket, "receive", cancellable, Glib::IO_IN);
        try {
            if (use_udp)
                size = recv_socket->receive_from (address,
                                                  buffer, sizeof buffer,
                                                  cancellable);
            else
                size = recv_socket->receive (buffer, sizeof buffer,
                                             cancellable);
        } catch (const Gio::Error& error)
        {
            std::cerr << Glib::ustring::compose ("Error receiving from socket: %1\n",
                                                 error.what ());
            return 1;
        }

        if (size == 0)
            break;

        std::cout << Glib::ustring::compose ("received %1 bytes of data", size);
        if (use_udp)
            std::cout << Glib::ustring::compose (" from %1", socket_address_to_string (address));
        std::cout << std::endl;

        if (verbose)
            g_print ("-------------------------\n"
                     "%.*s\n"
                     "-------------------------\n",
                     (int)size, buffer);

        auto to_send = size;

        while (to_send > 0)
        {
            ensure_condition (recv_socket, "send", cancellable, Glib::IO_OUT);
            try {
                if (use_udp)
                    size = recv_socket->send_to (address,
                                                 buffer, to_send, cancellable);
                else
                    size = recv_socket->send (buffer, to_send,
                                              cancellable);
            } catch (const Gio::Error& error)
            {
                if (error.code () == Gio::Error::WOULD_BLOCK)
                {
                    std::cout << "socket send would block, handling\n";
                    continue;
                }
                else
                {
                    std::cerr << Glib::ustring::compose ("Error sending to socket: %1\n",
                                                         error.what ());
                    return 1;
                }
            }

            std::cout << Glib::ustring::compose ("sent %1 bytes of data\n", size);

            if (size == 0)
            {
                std::cerr << "Unexpected short write\n";
                return 1;
            }

            to_send -= size;
        }
    }

    std::cout << "connection closed\n";

    if (new_socket)
    {
        try {
            new_socket->close ();
        } catch (const Gio::Error& error)
        {
            std::cerr << Glib::ustring::compose ("Error closing connection socket: %1\n",
                                                 error.what ());
            return 1;
        }
    }

    try {
        socket->close ();
    } catch (const Gio::Error& error)
    {
        std::cerr << Glib::ustring::compose ("Error closing master socket: %1\n",
                                             error.what ());
        return 1;
    }

    return 0;
}