Re: [gnet] gtk and gnet



On Wednesday 02 February 2005 13:48, Foxugly wrote:

> I try to make a program, something like msn, jabber,gaim. I read lot
> of thing about gtk, gnet, giochannel... but I don't understand how to
> combine the interface gtk and gnet..
>
> I want to change my interface when I receive an information from the
> network, but I don't know how  to do

If you use GNet in a Gnome/Gtk+ application, you generally want to do network
communication asynchronously/non-blocking, so that your GUI is still updated
and usable while the network communication is going on.

In GNet, there are two ways to achieve this:

(1) There is an asynchronous API that you pass your own callbacks to, like
GConn for TCP connections. When you create a TCP connection (GConn) via
gnet_conn_new(), you pass a callback function that is called whenever
something happens, like data that has arrived or the connection has been
terminated on the other side, etc. This will all work in the background as
long as the default GLib main context is running, which is the case when you
have a Gtk+ application and called gtk_main().

(2) There is no straight-forward callback-based async API, but there is a
function that returns the GIOChannel, e.g. GUDPSocket or GUnixSocket. In this
case you simply retrieve the GIOChannel, and then set up your callback
function using g_io_add_watch(), e.g.:

  GUdpSocket *udpsock;
  GIOChannel *ioc;

  udpsock = gnet_udp_socket_new ();

  ioc = gnet_udp_socket_get_io_channel (udpsock);
  g_io_add_watch (ioc, G_IO_IN | G_IO_PRIV | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
                             your_callback_function,
                             data_for_your_function);

  if (gnet_udp_socket_send (udpsocket, msg, msglen, dst_inetaddr) != 0)
    g_error ("gnet_udp_socket_send () failed!\n");

Now your callback will be called when UDP data arrives. Note that more than
one condition might have occured when your callback is called, so you need to
check for the conditions _bitwise_ and handle more than one condition
properly as well, e.g.

static gboolean
your_callback_func (GIOChannel *ioc, GIOCondition cond, gpointer yourdata)
{
  if (cond & (G_IO_IN | G_IO_PRIV))
  {
    /* if we get 0 bytes even though it signalled us
     *  that data is available, the socket is gone */
    if (gnet_udp_socket_receive (....) <= 0)
    {
       cond |= G_IO_HUP;
    }
  }

  if (cond & (G_IO_ERR | G_IO_NVAL | G_IO_HUP))
  {
     ... done with this socket for some reason ....
     return FALSE;
  }
}

Not sure if all of the above scenarios can actually occur with UDP sockets,
I'm mentioning it just for completeness ;-)

Cheers
 -Tim



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