0

我想在 gtk 中使用 gio 套接字编写一个客户端服务器的东西,我找到了一个将数据发送到服务器的示例代码,但是,我想要的更多的是读取服务器发送的数据/回复。下面是示例代码

#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;
}

上面的代码适用于向服务器发送数据,但是当我尝试从输入流中读取它时,它会进入阻塞状态。我的阅读消息功能看起来像这样

 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);
 }
4

1 回答 1

0

g_input_stream_read()被记录为阻塞,直到它接收到您请求的字节数(在本例中为 2048),或者直到连接关闭。据推测,这些事情都没有发生。服务器的回复有多大?发送回复后是否关闭连接?

请记住g_socket_client_connect_to_host()打开 TCP 连接,因此您应该期望在这里执行基于流的 I/O,而不是基于消息的 I/O。如果您希望向服务器发送消息或从服务器发送消息,则需要 TCP 内的帧协议。

于 2017-03-06T10:17:42.143 回答