1#include <gio/gio.h>
2#include <string.h>
3
4#define MESSAGE "Welcome to the echo service!\n"
5
6int port = 7777;
7static GOptionEntry cmd_entries[] = {
8 {"port", 'p', 0, G_OPTION_ARG_INT, &port,
9 "Local port to bind to", NULL},
10 {NULL}
11};
12
13
14static gboolean
15handler (GThreadedSocketService *service,
16 GSocketConnection *connection,
17 GSocketListener *listener,
18 gpointer user_data)
19{
20 GOutputStream *out;
21 GInputStream *in;
22 char buffer[1024];
23 gssize size;
24
25 out = g_io_stream_get_output_stream (G_IO_STREAM (connection));
26 in = g_io_stream_get_input_stream (G_IO_STREAM (connection));
27
28 g_output_stream_write_all (stream: out, MESSAGE, count: strlen (MESSAGE),
29 NULL, NULL, NULL);
30
31 while (0 < (size = g_input_stream_read (stream: in, buffer,
32 count: sizeof buffer, NULL, NULL)))
33 g_output_stream_write (stream: out, buffer, count: size, NULL, NULL);
34
35 return TRUE;
36}
37
38int
39main (int argc, char *argv[])
40{
41 GSocketService *service;
42 GOptionContext *context;
43 GError *error = NULL;
44
45 context = g_option_context_new (parameter_string: " - Test GSocket server stuff");
46 g_option_context_add_main_entries (context, entries: cmd_entries, NULL);
47 if (!g_option_context_parse (context, argc: &argc, argv: &argv, error: &error))
48 {
49 g_printerr (format: "%s: %s\n", argv[0], error->message);
50 return 1;
51 }
52
53 service = g_threaded_socket_service_new (max_threads: 10);
54
55 if (!g_socket_listener_add_inet_port (G_SOCKET_LISTENER (service),
56 port,
57 NULL,
58 error: &error))
59 {
60 g_printerr (format: "%s: %s\n", argv[0], error->message);
61 return 1;
62 }
63
64 g_print (format: "Echo service listening on port %d\n", port);
65
66 g_signal_connect (service, "run", G_CALLBACK (handler), NULL);
67
68 g_main_loop_run (loop: g_main_loop_new (NULL, FALSE));
69 g_assert_not_reached ();
70}
71

source code of gtk/subprojects/glib/gio/tests/echo-server.c