115 lines
2.7 KiB
C
115 lines
2.7 KiB
C
#include <stdio.h>
|
|
#include <common/util.h>
|
|
#include <glib.h>
|
|
#include <gio/gio.h>
|
|
|
|
int
|
|
main (int argc, char *argv[])
|
|
{
|
|
#ifdef DEBUG
|
|
setenv ("G_MESSAGES_DEBUG", "all", 1);
|
|
#endif
|
|
|
|
GError *error = NULL;
|
|
int PORT = SERVER_DEFAULT_PORT;
|
|
if (argc > 1)
|
|
{
|
|
PORT = atoi (argv[1]);
|
|
g_info ("Changed the listening port from default=%d to custom=%d",
|
|
SERVER_DEFAULT_PORT, PORT);
|
|
}
|
|
GSocket *socket = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM,
|
|
G_SOCKET_PROTOCOL_TCP, &error);
|
|
if (!socket)
|
|
{
|
|
g_printerr ("Socket creation failed: %s\n", error->message);
|
|
g_clear_error (&error);
|
|
return -1;
|
|
}
|
|
else
|
|
{
|
|
g_info ("Created TCP socket.");
|
|
}
|
|
|
|
GInetAddress *addr = g_inet_address_new_any (G_SOCKET_FAMILY_IPV4);
|
|
GSocketAddress *sockaddr = g_inet_socket_address_new (addr, PORT);
|
|
|
|
if (!g_socket_bind (socket, sockaddr, TRUE, &error))
|
|
{
|
|
g_printerr ("Bind failed: %s\n", error->message);
|
|
g_clear_error (&error);
|
|
g_object_unref (socket);
|
|
}
|
|
else
|
|
{
|
|
g_info ("Bound TCP socket to port %d", PORT);
|
|
}
|
|
|
|
g_object_unref (addr);
|
|
g_object_unref (sockaddr);
|
|
|
|
if (!g_socket_listen (socket, &error))
|
|
{
|
|
g_printerr ("Listen failed: %s\n", error->message);
|
|
g_clear_error (&error);
|
|
g_object_unref (socket);
|
|
return -1;
|
|
}
|
|
else
|
|
{
|
|
g_info ("TCP socket is now listening");
|
|
}
|
|
|
|
g_info ("Listening...");
|
|
while (true)
|
|
{
|
|
GSocket *socket2 = g_socket_accept (socket, NULL, &error);
|
|
GSocketConnection *connection =
|
|
g_socket_connection_factory_create_connection (socket2);
|
|
if (!connection)
|
|
{
|
|
g_printerr ("accept() failed: %s\n", error->message);
|
|
g_clear_error (&error);
|
|
continue;
|
|
}
|
|
else
|
|
{
|
|
g_info ("New connection accepted");
|
|
}
|
|
|
|
GInputStream *istream =
|
|
g_io_stream_get_input_stream (G_IO_STREAM (connection));
|
|
gchar buffer[1024];
|
|
gssize n =
|
|
g_input_stream_read (istream, buffer, sizeof (buffer) - 1, NULL,
|
|
&error);
|
|
|
|
if (n > 0)
|
|
{
|
|
buffer[n] = '\0';
|
|
g_print ("Received from client: %s\n", buffer);
|
|
}
|
|
else
|
|
{
|
|
g_printerr ("Read error: %s\n", error->message);
|
|
g_clear_error (&error);
|
|
}
|
|
|
|
GOutputStream *ostream =
|
|
g_io_stream_get_output_stream (G_IO_STREAM (connection));
|
|
const gchar *response =
|
|
"Hello from the librefront server. Not implemented!!";
|
|
g_output_stream_write (ostream, response, strlen (response), NULL,
|
|
&error);
|
|
g_output_stream_flush (ostream, NULL, &error);
|
|
|
|
g_io_stream_close (G_IO_STREAM (connection), NULL, NULL);
|
|
g_object_unref (connection);
|
|
g_object_unref (socket2);
|
|
}
|
|
|
|
g_object_unref (socket);
|
|
fprintf (stderr, "Server not implemented!\n");
|
|
return -1;
|
|
}
|