我正在学习gsocket,并想尝试编写一个简单的程序来处理我收到的任何数据包,但只有一个数据包来时,总是会调用函数回调。这是我的简单代码:
#include <glib.h>
#include <gio/gio.h>
#include <libsoup/soup.h>
#include <glib-object.h>
gboolean has_packet(GIOChannel *source, GIOCondition condition, gpointer data){
g_printf("has packet\n");
return TRUE;
}
int main(int argc, char **argv) {
g_type_init();
GInetAddress *iface_address = g_inet_address_new_from_string ("0.0.0.0");
GSocketAddress *bind_address = g_inet_socket_address_new (iface_address, 12345);
GSocket *sock;
GError *err = NULL;
sock = g_socket_new(G_SOCKET_FAMILY_IPV4,
G_SOCKET_TYPE_DATAGRAM,
G_SOCKET_PROTOCOL_UDP,
&err);
g_assert(err == NULL);
g_socket_bind(sock, bind_address, TRUE, &err);
g_assert(err == NULL);
//int fd = g_socket_get_fd(sock);
//GIOChannel* channel = g_io_channel_unix_new(fd);
//guint source = g_io_add_watch(channel, G_IO_IN,
// (GIOFunc) test, NULL);
//g_io_channel_unref(channel);
GSource *source = g_socket_create_source (sock, G_IO_IN,
NULL);
g_source_set_callback (source, (GSourceFunc)has_packet, NULL, NULL);
GMainLoop *loop = g_main_loop_new(NULL, FALSE);
g_source_attach(source ,g_main_loop_get_context(loop));
g_main_loop_run(loop);
g_main_loop_unref(loop);
}
我希望什么时候有一个数据包来,只有一个链接&#34;有数据包&#34;将打印,但它会永远运行。你能帮我解决一下我出错的地方吗。
更新:我需要在套接字中读取数据。
gboolean has_packet(GIOChannel *source, GIOCondition condition, gpointer data)
{
GSocket *sock = (GSocket *)data;
char buf[65536];
GSocketAddress *address = NULL;
gssize bytes;
GInputVector vector;
GSocketControlMessage **messages;
gint num_messages;
GError *error = NULL;
vector.buffer = buf;
vector.size = 65536;
bytes = g_socket_receive_message (sock,
&address,
&vector,
1,
&messages,
&num_messages,
NULL,
NULL,
&error);
g_printf("has packet\n");
g_printf("bytes = %zd\n", bytes);
g_printf("num_message = %d\n", num_messages);
return TRUE;
}
答案 0 :(得分:0)
如果你只想要一次调用它,你应该return FALSE
(或return G_SOURCE_REMOVE
)。
此外,您使用g_main_loop_run()
启动主循环,这将永远运行,直到调用g_main_loop_quit()
。所以你应该在某个时候退出主循环(可能是你希望它在收到数据包后退出,所以你应该在g_main_loop_quit()
中调用has_packet()
。