| 1 |
#include <gio/gio.h> |
| 2 |
#include <string.h> |
| 3 |
|
| 4 |
#define MESSAGE "Welcome to the echo service!\n" |
| 5 |
|
| 6 |
int port = 7777; |
| 7 |
static GOptionEntry cmd_entries[] = { |
| 8 |
{"port", 'p', 0, G_OPTION_ARG_INT, &port, |
| 9 |
"Local port to bind to", NULL}, |
| 10 |
G_OPTION_ENTRY_NULL |
| 11 |
}; |
| 12 |
|
| 13 |
|
| 14 |
static gboolean |
| 15 |
handler (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 (out, MESSAGE, strlen (MESSAGE), |
| 29 |
NULL, NULL, NULL); |
| 30 |
|
| 31 |
while (0 < (size = g_input_stream_read (in, buffer, |
| 32 |
sizeof buffer, NULL, NULL))) |
| 33 |
g_output_stream_write (out, buffer, size, NULL, NULL); |
| 34 |
|
| 35 |
return TRUE; |
| 36 |
} |
| 37 |
|
| 38 |
int |
| 39 |
main (int argc, char *argv[]) |
| 40 |
{ |
| 41 |
GSocketService *service; |
| 42 |
GOptionContext *context; |
| 43 |
GError *error = NULL; |
| 44 |
|
| 45 |
context = g_option_context_new (" - Test GSocket server stuff"); |
| 46 |
g_option_context_add_main_entries (context, cmd_entries, NULL); |
| 47 |
if (!g_option_context_parse (context, &argc, &argv, &error)) |
| 48 |
{ |
| 49 |
g_printerr ("%s: %s\n", argv[0], error->message); |
| 50 |
return 1; |
| 51 |
} |
| 52 |
|
| 53 |
service = g_threaded_socket_service_new (10); |
| 54 |
|
| 55 |
if (!g_socket_listener_add_inet_port (G_SOCKET_LISTENER (service), |
| 56 |
port, |
| 57 |
NULL, |
| 58 |
&error)) |
| 59 |
{ |
| 60 |
g_printerr ("%s: %s\n", argv[0], error->message); |
| 61 |
return 1; |
| 62 |
} |
| 63 |
|
| 64 |
g_print ("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 (g_main_loop_new (NULL, FALSE)); |
| 69 |
g_assert_not_reached (); |
| 70 |
} |