Need help implementing simple socket server using GIOService (GLib, Glib-GIO)

前端 未结 3 938
半阙折子戏
半阙折子戏 2020-12-30 18:22

I\'m learning the basics of writing a simple, efficient socket server using GLib. I\'m experimenting with GSocketService. So far I can only seem to accept connections but th

3条回答
  •  清酒与你
    2020-12-30 18:42

    It's not documented in the GSocketService docs (I had to go through the GLib sources to find it), but the routine that calls the callback (new_connection in this case) *does a g_object_unref() on the connection object* after it returns. This effectively closes the connection immediately new_connection() returns to it.

    I have no idea why it does this, but the solution is to add a g_object_ref() on entering the callback:

    gboolean
    new_connection(GSocketService *service,
                  GSocketConnection *connection,
                  GObject *source_object,
                  gpointer user_data)
    {
    
      g_object_ref(connection);    /* Tell glib not to disconnect */
    
      GSocketAddress *sockaddr = g_socket_connection_get_remote_address(connection, NULL);
      GInetAddress *addr =
          g_inet_socket_address_get_address(G_INET_SOCKET_ADDRESS(sockaddr));
      guint16 port = g_inet_socket_address_get_port(G_INET_SOCKET_ADDRESS(sockaddr));
    

    Without that addition, polling the file descriptor in the main loop just returned POLLNVAL because the connection had been closed. In the absence of a handler for that result, it did that continuously -- and that's what caused the 100% CPU load.

提交回复
热议问题