Re: Network event somewhere?



Kenneth �tby <kenneth.ostby <at> gmail.com> writes:

> It seems like what you're looking for is the magical GIOChannel to which you
> can create out of your already opened filedescriptor. That solves the whole 
> select magic for you. 
> 1. Open socket
> 2. Create new GIOChannel with the filedescriptor
> 3. Add a GIO watch with g_io_add_watch()

Thank you, that was just what I've been looking for. And because Magnus
Therning asked me to let the people on this list know if I made it work,
here's some sample code:

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <gtk/gtk.h>


gboolean
my_process_connect (GIOChannel * source,
                    GIOCondition condition, gpointer data)
{
  int work_fd;
  unsigned int client_addr_len;
  struct sockaddr_in client_addr;

  work_fd =
    accept (*((int *) data), (struct sockaddr *) &client_addr,
            &client_addr_len);
  printf ("connection from port %d\n", ntohs (client_addr.sin_port));
  close (work_fd);
  return TRUE;
}

void
myquit (GtkWidget * widget, gpointer data)
{
  printf ("bye\n");
  gtk_main_quit ();
}

int
main (int argc, char **argv)
{
  int listen_fd;
  struct sockaddr_in my_addr;
  GIOChannel *myiochannel;
  GtkWidget *mywin, *mylabel;

  gtk_init (&argc, &argv);

  listen_fd = socket (AF_INET, SOCK_STREAM, 0);
  my_addr.sin_family = AF_INET;
  my_addr.sin_addr.s_addr = INADDR_ANY;
  my_addr.sin_port = htons (10000);
  bind (listen_fd, (struct sockaddr *) &my_addr, sizeof (my_addr));
  listen (listen_fd, 5);

  myiochannel = g_io_channel_unix_new (listen_fd);
  g_io_add_watch (myiochannel, G_IO_IN, my_process_connect, &listen_fd);

  mywin = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title (GTK_WINDOW (mywin), "network event");
  gtk_window_set_policy (GTK_WINDOW (mywin), FALSE, TRUE, FALSE);
  gtk_container_set_border_width (GTK_CONTAINER (mywin), 5);

  gtk_signal_connect (GTK_OBJECT (mywin), "delete_event",
                      GTK_SIGNAL_FUNC (myquit), NULL);

  mylabel = gtk_label_new ("network event sample code");
  gtk_container_add (GTK_CONTAINER (mywin), mylabel);
  gtk_widget_show_all (mywin);
  gtk_main ();
  return 0;
}

After compiling and starting, you can easily test it with "telnet localhost
10000".


cu

   Mario




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]