#include <glib.h>

#ifdef _WIN32
# include <winsock2.h>
#else
# include <sys/socket.h>
# include <sys/types.h>
# include <netinet/in.h>
# define SOCKET int
#endif

gboolean on_idle(gpointer data)
{
	return FALSE;
}

gboolean on_io_out(GIOChannel* source, GIOCondition condition, gpointer data)
{
	g_print("data can be written\n");
	return FALSE;
}

gboolean on_timeout(gpointer io_channel)
{
	GIOChannel* channel = (GIOChannel*)io_channel;

	g_io_add_watch(channel, G_IO_OUT, on_io_out, NULL);
	/*g_idle_add(on_idle, NULL);*/

	return FALSE;
}

int main()
{
#ifdef _WIN32
	WSADATA data;
#endif
	SOCKET sock;
	GIOChannel* channel;
	GMainLoop* mainloop;
	struct sockaddr_in local_addr;

#ifdef _WIN32
	WSAStartup(MAKEWORD(2, 0), &data);
#endif

	mainloop = g_main_loop_new(NULL, FALSE);

	local_addr.sin_family = AF_INET;
	local_addr.sin_port = 32501;
	local_addr.sin_addr.s_addr = INADDR_LOOPBACK;

	sock = socket(PF_INET, SOCK_DGRAM, 0);

	bind(sock, (struct sockaddr*)&local_addr, sizeof(local_addr) );

#ifdef _WIN32
	channel = g_io_channel_win32_new_socket(sock);
#else
	channel = g_io_channel_unix_new(sock);
#endif

	g_timeout_add(100, on_timeout, channel);

	g_main_loop_run(mainloop);

	return 0;
}
