Re: [gnet] non-blocking UDP sockets



On Tue, 2006-10-31 at 11:10 -0500, Mark Drago wrote:

Hi Mark,

> I use GTcpSocket in a non-blocking way by calling
> gnet_tcp_socket_get_io_channel() to get the GIOChannel and then using
> g_io_channel_set_flags() to flip the G_IO_FLAG_NONBLOCK bit.  Then,
> whenever I want to read or write to the socket I use
> g_io_channel_read/write_chars() directly.  This is working out fine.

You have seen the GConn API providing an async wrapper for GTcpSocket,
right?

> I am wondering how I would be able to do the same thing with UDP
> sockets.  The GUdpSocket documentations says the following:
> "gnet_udp_socket_send() will block if the OS cannot buffer the packet
> immediately. gnet_udp_socket_receive() will block until there is a
> packet available to receive."  But, it also says the following: "Note
> that a UDP socket's GIOChannel is not a normal GIOChannel -- it should
> not be written to or read from directly."

I think the latter remark means that you shouldn't use GIOChannel
functions for reading or writing data to this special UDP GIOChannel,
but only gnet_udp_socket_receive() and _send().

You should still be able to do async I/O on this GIOChannel the usual
way, namely by setting up an IO watch with g_io_add_watch(). Use the
G_IO_IN flag to be notified whenever a packet arrives (which you can
then read without blocking using gnet_udp_socket_receive()) and the
G_IO_OUT flag to be notified whenever the socket is ready for sending
data (you will probably need to remove the watch and set up a new
read-only one again once you've sent all your data, or your callback
will be called all the time with 'ready to send').

Another thing to take care of: before closing/deleting the udp socket,
remove your IO watch again with g_source_remove() passing the ID you got
from g_io_add_watch(), otherwise GLib might going to go into a busy loop
polling an invalid/closed fd in the next main loop iteration.

 Cheers
  -Tim





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