1 /* ttt-client.c - client handling code for tic-tac-toe game server
3 * Copyright © 2005 Carl Worth
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2, or (at your option)
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software Foundation,
17 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19 * Author: Carl Worth <cworth@cworth.org>
22 #include "ttt-client.h"
23 #include "ttt-socket.h"
26 ttt_client_create (ttt_server_t *server, int socket, int id)
30 client = xmalloc (sizeof (ttt_client_t));
32 client->server = server;
33 client->socket = socket;
37 client->buf_head = client->buf;
38 client->buf_tail = client->buf;
40 client->request = NULL;
41 client->request_size = 0;
42 client->request_len = 0;
48 ttt_client_destroy (ttt_client_t *client)
50 shutdown (client->socket, SHUT_RDWR);
52 free (client->request);
58 _append_to_request (ttt_client_t *client,
62 int size_needed = client->request_len + size;
64 if (size_needed > client->request_size) {
65 if (client->request_size == 0) {
66 client->request_size = size_needed;
68 while (size_needed > client->request_size)
69 client->request_size *= 2;
72 client->request = xrealloc (client->request, client->request_size);
75 memcpy (client->request + client->request_len,
78 client->request_len += size;
82 ttt_client_read_into_request_until (ttt_client_t *client, char delimeter)
84 ttt_bool_t found_delimeter = FALSE;
88 client->request_len = 0;
92 if (client->buf_tail >= client->buf_head) {
93 bytes_read = xread (client->socket,
97 return TTT_STATUS_EOF;
98 client->buf_head = client->buf;
99 client->buf_tail = client->buf_head + bytes_read;
102 for (s = client->buf_head; s < client->buf_tail; s++) {
103 if (*s == delimeter) {
104 found_delimeter = TRUE;
110 _append_to_request (client,
112 s - client->buf_head);
113 client->buf_head = s;
116 return TTT_STATUS_SUCCESS;
121 ttt_client_read_line (ttt_client_t *client)
124 static const char null_terminator = '\0';
126 status = ttt_client_read_into_request_until (client, '\n');
128 assert (status == TTT_STATUS_EOF);
132 _append_to_request (client, &null_terminator, 1);
134 return client->request;
138 ttt_client_send (ttt_client_t *client, const char *message)
140 ttt_socket_write (client->socket, message, strlen (message));