summaryrefslogtreecommitdiff
path: root/server_communication.c
blob: f331a3539760949b00d8fc299365c0cddb64ec61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include "server_communication.h"
#include "music.h"

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

static GSocket *server_connect(struct server *server) {
	GError *error = NULL, *conn_error = NULL;
	GSocketConnectable *addr;
	GSocketAddressEnumerator *enumerator;
	GSocketAddress *sockaddr;
	GSocketConnection *conn = NULL;
	GSocketClient *client;

	addr = g_network_address_new(server->host, server->port);
	enumerator = g_socket_connectable_enumerate(addr);
	g_object_unref(addr);

	client = g_socket_client_new();

	while(conn == NULL && (sockaddr = g_socket_address_enumerator_next(enumerator, NULL, &error))) {
		conn = g_socket_client_connect(client, (GSocketConnectable*)sockaddr, NULL, &conn_error);
		g_object_unref(sockaddr);
	}

	if(sockaddr == NULL) {
		if(error != NULL) {
			g_warning(error->message);
			g_error_free(error);
		} else {
			g_warning("server_connect: no connectable addresses found for host %s",
					server->host);
		}
		return NULL;
	}

	if(conn == NULL) {
		g_warning(conn_error->message);
		g_error_free(conn_error);
		return NULL;
	}

	GSocket *socket = g_socket_connection_get_socket(conn);

	g_debug("connected");

	return socket;
}

gboolean server_ping(struct server *server) {
	GTimer *timer = g_timer_new();
	GSocket *socket = server_connect(server);

	if(socket == NULL) {
		return FALSE;
	}

	gboolean result = FALSE;
	g_socket_send(socket, "ping\n", 5, NULL, NULL);
	gchar buffer[0x400];
	gssize size = g_socket_receive(socket, buffer, 0x400, NULL, NULL);
	if(size == 5 && strncmp(buffer, "pong", 4) == 0) {
		g_debug("ping response: %f ms", g_timer_elapsed(timer, NULL) * 1000);
		result = TRUE;
	}

	g_timer_destroy(timer);

	g_socket_close(socket, NULL);

	return result;
}

gchar **server_find(struct server *server, const gchar *type, const gchar *str) {
	GSocket *socket = server_connect(server);

	if(socket == NULL) {
		return NULL;
	}

	gchar buffer[0x400];
	g_snprintf(buffer, 0x400, "find %s %s\nexit\n", type, str);
	g_socket_send(socket, buffer, strlen(buffer), NULL, NULL);

	gssize size;
	GString *string = g_string_new(NULL);
	while((size = g_socket_receive(socket, buffer, 0x400, NULL, NULL)) > 0) {
		g_string_append_len(string, buffer, size);
	}

	g_socket_close(socket, NULL);

	gchar **data = g_strsplit(string->str, "\n", 0);
	g_string_free(string, TRUE);

	return data;
}