gpt4 book ai didi

sockets - GIO 套接字服务器/客户端示例

转载 作者:行者123 更新时间:2023-12-03 18:29:03 31 4
gpt4 key购买 nike

我想创建一个使用 GIO 通过套接字进行通信的服务器和客户端应用程序。 GSocketService 和 GSocketClient 似乎非常适合此目的,但不幸的是我找不到一些教程或示例代码(GLib,GIO,......新手可以理解)。有人知道一些好的资源或可以在这里发布示例代码吗?

最佳答案

我终于设法使用 glib 和 gio 创建了一个简单的服务器和客户端。
我的服务器看起来像这样:

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

/* this function will get called everytime a client attempts to connect */
gboolean
incoming_callback (GSocketService *service,
GSocketConnection *connection,
GObject *source_object,
gpointer user_data)
{
g_print("Received Connection from client!\n");
GInputStream * istream = g_io_stream_get_input_stream (G_IO_STREAM (connection));
gchar message[1024];
g_input_stream_read (istream,
message,
1024,
NULL,
NULL);
g_print("Message was: \"%s\"\n", message);
return FALSE;
}

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

GError * error = NULL;

/* create the new socketservice */
GSocketService * service = g_socket_service_new ();

/* connect to the port */
g_socket_listener_add_inet_port ((GSocketListener*)service,
1500, /* your port goes here */
NULL,
&error);

/* don't forget to check for errors */
if (error != NULL)
{
g_error (error->message);
}

/* listen to the 'incoming' signal */
g_signal_connect (service,
"incoming",
G_CALLBACK (incoming_callback),
NULL);

/* start the socket service */
g_socket_service_start (service);

/* enter mainloop */
g_print ("Waiting for client!\n");
GMainLoop *loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
return 0;
}

这是相应的客户端:

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

不过请注意,我对 glib、gio 甚至 C 仍然是新手,所以在使用之前请仔细检查我的代码。

关于sockets - GIO 套接字服务器/客户端示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9513327/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com