hedgehog/software/ GlibUdpListenerExample001
We use g_socket_new
to open a socket and create a GIOChannel
objct.
#include <gio/gio.h>
#include <glib.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BLOCK_SIZE 1024
#define GG g_print("line %d\n",__LINE__)
static gboolean
gio_read_socket (GIOChannel *channel,
GIOCondition condition,
gpointer data)
{
static int r = 0;
r++;
printf("r=%d\n",r);
char buf[1024];
gsize bytes_read;
GError *error = NULL;
g_print("gio_read_socket\n");
if (condition & G_IO_HUP) return FALSE; /* this channel is done */
GG;
g_print("channel not done\n");
// g_io_channel_read (channel, buf, sizeof (buf), &bytes_read);
g_io_channel_read_chars (channel, buf, sizeof (buf), &bytes_read, &error);
g_print("g_io_channel_read_chars\n");
g_print("%ld bytes read\n",bytes_read);
g_assert (error == NULL);
GG;
buf[bytes_read] = '\0';
g_print ("%s", buf);
int i=0,l=32;
for(int i=0; i<bytes_read && i<sizeof(buf); i++) {
printf("%02x ",buf[i]);
if( (i+1) % l == 0 ) {
printf("\n");
}
}
if( (i % l) != 0 ) {
printf("\n");
}
int *a = data;
*a = *a + 1;
return TRUE;
}
gboolean
idleCpt (gpointer user_data){
int *a = user_data;
g_print("hello\n");
g_print("%d\n", *a);
usleep(10000);
return TRUE;
}
int
main (int argc, char **argv)
{
GSocket * s_udp;
GError *err = NULL;
int idIdle = -1, dataI = 0;
guint16 udp_port = 4001;
GSocketAddress * gsockAddr = G_SOCKET_ADDRESS(g_inet_socket_address_new(g_inet_address_new_any(G_SOCKET_FAMILY_IPV4), udp_port));
s_udp = g_socket_new(G_SOCKET_FAMILY_IPV4,
G_SOCKET_TYPE_DATAGRAM,
G_SOCKET_PROTOCOL_UDP,
&err);
g_assert(err == NULL);
if (s_udp == NULL) {
g_print("ERREUR");
exit(1);
}
if (g_socket_bind (s_udp, gsockAddr, TRUE, NULL) == FALSE){
g_print("Erreur bind\n");
exit(1);
}
g_assert(err == NULL);
int fd = g_socket_get_fd(s_udp);
GIOChannel* channel = g_io_channel_unix_new(fd);
g_io_channel_set_encoding ( channel, NULL , &err );
g_assert(err == NULL);
guint source = g_io_add_watch(channel, G_IO_IN,
(GIOFunc) gio_read_socket, &dataI);
g_io_channel_unref(channel);
GMainLoop *loop = g_main_loop_new(NULL, FALSE);
idIdle = g_idle_add(idleCpt, &dataI);
g_main_loop_run(loop);
}