1 /* ttt-server.c - 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>
23 #include "ttt-client.h"
24 #include "ttt-socket.h"
27 pthread_mutex_t mutex;
29 ttt_client_t **clients;
34 ttt_server_init (ttt_server_t *server)
36 pthread_mutex_init (&server->mutex, NULL);
38 server->clients = NULL;
39 server->num_clients = 0;
43 ttt_server_add_client (ttt_server_t *server, ttt_client_t *client)
45 pthread_mutex_lock (&server->mutex);
47 server->num_clients++;
48 server->clients = xrealloc (server->clients,
49 server->num_clients * sizeof (ttt_client_t *));
51 server->clients [server->num_clients - 1] = client;
53 pthread_mutex_unlock (&server->mutex);
57 _accept_client (void *closure, int client_socket)
59 ttt_server_t *server = closure;
62 client = ttt_client_create (server, client_socket);
64 ttt_server_add_client (server, client);
66 ttt_client_handle_requests (client);
69 static const char *WELCOME_MESSAGE =
70 "Welcome to ttt-server. So far, this program is simply a demonstration\n"
71 "of a TCP/IP server capable of handling multiple simultaneous clients.\n"
72 "The server is currently listening on:\n"
74 "\nTo test this program, simply connect a client to that host and port.\n"
77 "\nOnce you have connected a client, the server will echo any characters\n"
78 "it receives back to the client as well as to stdout.\n"
79 "\nNote that to terminate the telnet client you type Control-], then\n"
80 "<Enter>, then \"close\" (and <Enter>) at the \"telnet> \" prompt.\n"
83 "\nPS. The server does support multiple clients, but there is not yet any\n"
84 "interaction between the clients. The next step is probably to turn the\n"
85 "server into a simple chat server. After that, we should have the necessary\n"
86 "structure in place to start implementing the real tic-tac-toe protocol.\n\n";
89 main (int argc, char **argv)
95 ttt_args_parse (&args, argc, argv);
98 xfreopen (args.log_file, "a", stderr);
100 socket = ttt_socket_create_server (args.host, args.port);
102 printf (WELCOME_MESSAGE, args.host, args.port, args.host, args.port);
104 ttt_server_init (&server);
107 ttt_socket_accept (socket, _accept_client, &server);
109 /* We only reach here if something bad happened. */