0

I wanted to write a client server thing using gio socket in gtk and I found a sample code to send data to server but, the more thing i want is to read the data/reply sent by the server. The below is sample code

#include <glib.h>
#include <gio/gio.h>

int main (int argc, char *argv[])
{
   /* initialize glib */
  g_type_init ();

  GError * error = NULL;

  /* create a new connection */
  GSocketConnection * connection = NULL;
  GSocketClient * client = g_socket_client_new();

  /* connect to the host */
  connection = g_socket_client_connect_to_host (client,
                                           (gchar*)"localhost",
                                            1500, /* your port goes here */
                                            NULL,
                                            &error);

  /* don't forget to check for errors */
  if (error != NULL)
  {
      g_error (error->message);
  }
  else
  {
      g_print ("Connection successful!\n");
  }

  /* use the connection */
  GInputStream * istream = g_io_stream_get_input_stream (G_IO_STREAM (connection));
  GOutputStream * ostream = g_io_stream_get_output_stream (G_IO_STREAM (connection));
  g_output_stream_write  (ostream,
                      "Hello server!", /* your message goes here */
                      13, /* length of your message */
                      NULL,
                      &error);
  /* don't forget to check for errors */
  if (error != NULL)
  {
      g_error (error->message);
  }
  return 0;
}

The above code works fine for the sending data to server but when i try to read it form input stream it goes in to block state. My read message function look like this

 void readMessage()
 {
    char buffer[2048];
    GInputStream * istream = g_io_stream_get_input_stream (G_IO_STREAM(connection));
    gssize bytes;
    bytes = g_input_stream_read(istream, buffer, sizeof buffer, NULL, NULL);
    buffer[bytes] = '\0';
    g_print ("%"G_GSSIZE_FORMAT" bytes read: %s\n", bytes, buffer);
 }
Swapnil
  • 389
  • 5
  • 22

1 Answers1

0

g_input_stream_read() is documented as blocking until it receives as many bytes as you request (in this case, 2048), or until the connection is closed. Presumably, neither of those things are happening. How big is the reply from the server? Does it close the connection after sending its reply?

Bear in mind that g_socket_client_connect_to_host() opens a TCP connection, so you should expect to be doing stream-based I/O here, rather than message-based I/O. If you expect to be sending messages to and from the server, you will need a framing protocol within TCP.

Philip Withnall
  • 5,293
  • 14
  • 28