写一个使用GSocket发送tcp数据的例子,要有错误处理
时间: 2024-04-07 22:31:34 浏览: 216
好的,以下是一个使用GSocket发送TCP数据的例子,同时包含错误处理:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <glib.h>
#include <gio/gio.h>
#define BUF_SIZE 1024
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <host> <port>\n", argv[0]);
return 1;
}
const char *host = argv[1];
const char *port = argv[2];
// 初始化GIO库
g_type_init();
// 创建客户端socket
GSocketClient *client = g_socket_client_new();
if (client == NULL) {
fprintf(stderr, "Failed to create socket client: %s\n", strerror(errno));
return 1;
}
// 连接服务器
GSocketConnection *conn = g_socket_client_connect_to_host(client, host, atoi(port), NULL, NULL);
if (conn == NULL) {
fprintf(stderr, "Failed to connect to %s:%s: %s\n", host, port, strerror(errno));
g_object_unref(client);
return 1;
}
// 获取socket
GSocket *sock = g_socket_connection_get_socket(conn);
if (sock == NULL) {
fprintf(stderr, "Failed to get socket: %s\n", strerror(errno));
g_object_unref(conn);
g_object_unref(client);
return 1;
}
// 发送数据
char buf[BUF_SIZE];
strcpy(buf, "Hello, world!");
size_t len = strlen(buf);
GError *error = NULL;
gssize ret = g_socket_send(sock, buf, len, NULL, &error);
if (error != NULL) {
fprintf(stderr, "Failed to send data: %s\n", error->message);
g_error_free(error);
g_object_unref(sock);
g_object_unref(conn);
g_object_unref(client);
return 1;
} else if (ret != len) {
fprintf(stderr, "Failed to send all data: %zd/%zd\n", ret, len);
g_object_unref(sock);
g_object_unref(conn);
g_object_unref(client);
return 1;
}
// 关闭socket
g_socket_close(sock, NULL);
g_object_unref(sock);
g_object_unref(conn);
g_object_unref(client);
return 0;
}
```
在上述代码中,我们首先使用 `g_socket_client_new()` 函数创建一个socket客户端,然后使用 `g_socket_client_connect_to_host()` 函数连接到指定的服务器。如果连接失败,我们会输出错误信息并退出程序。
接着,我们使用 `g_socket_connection_get_socket()` 函数获取到socket对象,然后使用 `g_socket_send()` 函数发送数据。如果发送失败,我们同样会输出错误信息并退出程序。
最后,我们使用 `g_socket_close()` 函数关闭socket,并使用 `g_object_unref()` 函数释放内存。
注意,这只是一个简单的例子,实际应用中需要根据具体情况进行错误处理和异常处理。
阅读全文
相关推荐














