]> git.cworth.org Git - ttt/blobdiff - src/ttt-server.c
2005-11-14 Carl Worth <cworth@cworth.org>
[ttt] / src / ttt-server.c
index a248fa1a789b0a22f20db04551f0f531aaf472d5..2bc3a529b51efca60af87679488e248facd84b46 100644 (file)
@@ -1,4 +1,4 @@
-/* ttt.c - client-server tic-tac-toe game
+/* ttt-server.c - tic-tac-toe game server
  *
  * Copyright © 2005 Carl Worth
  *
  */
 
 #include "ttt.h"
+#include "ttt-args.h"
+#include "ttt-client.h"
+#include "ttt-socket.h"
 
-static ttt_status_t
-_sockaddr_init (struct sockaddr_in     *addr,
-               const char              *host,
-               const char              *port)
+struct _ttt_server {
+    pthread_mutex_t mutex;
+
+    int next_client_id;
+
+    ttt_client_t **clients;
+    int clients_size;
+    int num_clients;
+};
+
+static void
+ttt_server_init (ttt_server_t *server)
 {
-    struct hostent *hostent;
-    struct servent *servent;
-    char *endptr;
-    long port_long;
-    uint16_t port_short;
-
-    addr->sin_family = AF_INET;
-
-    hostent = gethostbyname (host);
-    if (hostent == NULL)
-    {
-       fprintf (stderr, "Error: Lookup failed for host %s: %s\n",
-                host, hstrerror (h_errno));
-       return TTT_STATUS_FAILURE;
-    }
-    memcpy (&addr->sin_addr.s_addr, hostent->h_addr_list[0], 
-           sizeof (addr->sin_addr.s_addr));
-
-    assert (*port != '\0');
-    port_long = strtol (port, &endptr, 10);
-    if (*endptr == '\0')
-    {
-       /* Numeric port*/
-       if (port_long <= 0 || port_long >= (1 << 16)) {
-           fprintf (stderr, "Error: Port %ld out of range.\n", port_long);
-           return TTT_STATUS_FAILURE;
-       }
-       port_short = port_long;
-       addr->sin_port = htons (port_short);
-    } else {
-       /* Named port */
-       servent = getservbyname (port, "tcp");
-       if (port == NULL) {
-           fprintf (stderr, "Error: Lookup failed for port %s: %s\n",
-                    port, hstrerror (h_errno));
-           return TTT_STATUS_FAILURE;
-       }
-       addr->sin_port = servent->s_port;
+    pthread_mutex_init (&server->mutex, NULL);
+
+    server->next_client_id = 0;
+
+    server->clients = NULL;
+    server->clients_size = 0;
+    server->num_clients = 0;
+}
+
+static ttt_client_t *
+ttt_server_create_client (ttt_server_t *server, int client_socket)
+{
+    ttt_client_t *client;
+
+    pthread_mutex_lock (&server->mutex);
+
+    client = ttt_client_create (server, client_socket,
+                               server->next_client_id++);
+
+    printf ("Client %d has joined.\n", client->id);
+
+    server->num_clients++;
+
+    if (server->num_clients > server->clients_size) {
+       if (server->clients_size == 0)
+           server->clients_size = 1;
+       else
+           server->clients_size *= 2;
+
+       server->clients = xrealloc (server->clients,
+                                   server->clients_size * sizeof (ttt_client_t *));
     }
 
-    return TTT_STATUS_SUCCESS;
+    server->clients [server->num_clients - 1] = client;
+
+    pthread_mutex_unlock (&server->mutex);
+
+    return client;
 }
 
-static int
-_wait_for_connection (int listen_socket)
+static void
+ttt_server_destroy_client (ttt_server_t *server, ttt_client_t *client)
 {
-    fd_set read_set;
-    int num_selected;
-    int flags, err;
-    int connected_socket;
+    int i;
 
-    FD_ZERO (&read_set);
-    FD_SET (listen_socket, &read_set);
+    pthread_mutex_lock (&server->mutex);
 
-    while (1) {
-       num_selected = select (listen_socket + 1,
-                              &read_set, NULL, NULL,
-                              NULL);
+    for (i = 0; i < server->num_clients; i++)
+       if (server->clients[i] == client)
+           break;
+
+    assert (i < server->num_clients);
+
+    printf ("Client %d has left.\n", client->id);
+
+    memmove (&server->clients[i], &server->clients[i+1],
+            (server->num_clients - i - 1) * sizeof (ttt_client_t *));
+
+    server->num_clients--;
+
+    ttt_client_destroy (client);
 
-       flags = fcntl (listen_socket, F_GETFL);
-       flags |= O_NONBLOCK;
-       xfcntl (listen_socket, F_SETFL, flags);
+    pthread_mutex_unlock (&server->mutex);
+}
+
+static void *
+_handle_client_requests_thread (void *closure)
+{
+    ttt_client_t *client = closure;
+    ttt_server_t *server = client->server;
+    char *request;
 
-       connected_socket = accept (listen_socket, 0, 0);
-       err = errno;
+    while (1) {
+
+       request = ttt_client_read_line (client);
+       if (request == NULL)
+           break;
 
-       flags &= ~O_NONBLOCK;
-       xfcntl (listen_socket, F_SETFL, flags);
+       ttt_server_broadcast (client->server, request);
+    }
 
-       if (connected_socket != -1)
-           return connected_socket;
+    ttt_server_destroy_client (server, client);
 
-       if (err == EWOULDBLOCK || err == EAGAIN)
-           continue;
+    return (void *) 0;
+}
 
-       fprintf (stderr, "Error: accept failed: %s. Aborting.\n",
+static void
+_accept_client (void *closure, int client_socket)
+{
+    ttt_server_t *server = closure;
+    ttt_client_t *client;
+    int err;
+    
+    client = ttt_server_create_client (server, client_socket);
+
+    err = pthread_create (&client->thread, NULL,
+                         _handle_client_requests_thread, client);
+    if (err != 0) {
+       fprintf (stderr, "Error: pthread_create failed: %s. Aborting.\n",
                 strerror (err));
        exit (1);
     }
 }
 
+void
+ttt_server_broadcast (ttt_server_t *server, const char *message)
+{
+    int i;
+
+    pthread_mutex_lock (&server->mutex);
+
+    for (i = 0; i < server->num_clients; i++)
+       ttt_client_send (server->clients[i], message);
+
+    pthread_mutex_unlock (&server->mutex);
+}
+
 static const char *WELCOME_MESSAGE = 
-"Welcome to ttt-server. So far, this program is simply a demonstration\n"
-"of a one-shot TCP/IP server. The server is currently listening on:\n"
+"Welcome to ttt-server. So far, this program is still a demonstration\n"
+"TCP/IP server, acting something like a rather braindead chat server.\n"
+"The server is currently listening on:\n"
 "\n    %s:%s\n"
-"\nTo test this program, simply connect a client to that host and port.\n"
+"\nTo test this, simply connect one or more clients to that host and port.\n"
 "For example:\n"
 "\n    telnet %s %s\n"
-"\nOnce you have connected a client, the server will echo any characters\n"
-"it receives back to the client as well as to stdout.\n"
+"\nOnce you have connected a client, the server will send each line of text\n"
+"it receives to all connected clients. The server reports client joins and\n"
+"departures on stdout.\n"
 "\nNote that to terminate the telnet client you type Control-], then\n"
 "<Enter>, then \"close\" (and <Enter>) at the \"telnet> \" prompt.\n"
 "\nHave fun!\n"
 "-Carl\n"
-"\nPS. By one-shot, I mean that the server will only accept a connection\n"
-"from a single client, and the server will exit when that client disconnects\n"
-"To test the server again, you will need to manually restart it again.\n"
-"Extending the server to start listening again, or to handle multiple\n"
-"clients simultaneously would both be fun projects for a motivated\n"
-"student (as would writing a custom client program).\n\n";
+"\nPS. At this point we're ready to leave the demonstration phase and to\n"
+"begin implementing TTTP (tic-tac-toe protocol) as well as fixing the\n"
+"protocol specifcation. We don't need a custom client to move forward on\n"
+"the server (that is one of the ideas behind using a telnet-compatible\n"
+"protocol), but a custom client would still be a fine project for a\n"
+"motivated beginning programmer.\n\n";
 
 int 
 main (int argc, char **argv)
 {
     ttt_args_t args;
-    int args_first;
-    int listen_socket, connected_socket;
-    struct sockaddr_in addr;
-
-    ttt_args_parse (&args, argc, argv, &args_first);
-
-    listen_socket = xsocket (PF_INET, SOCK_STREAM, 0);
-
-#define HOST "localhost"
-#define PORT "5534"
+    ttt_server_t server;
+    int socket;
 
-    _sockaddr_init (&addr, HOST, PORT);
+    ttt_args_parse (&args, argc, argv);
 
-#ifdef SO_REUSEADDR
-    {
-       int one = 1;
-       setsockopt (listen_socket, SOL_SOCKET,
-                   SO_REUSEADDR, (char *) &one, sizeof (int));
-    }
-#endif
-
-    xbind (listen_socket, (struct sockaddr *) &addr, sizeof (addr));
-
-    xlisten (listen_socket, SOMAXCONN);
+    if (args.log_file)
+       xfreopen (args.log_file, "a", stderr);
 
-    printf (WELCOME_MESSAGE, HOST, PORT, HOST, PORT);
+    socket = ttt_socket_create_server (args.host, args.port);
 
-    connected_socket = _wait_for_connection (listen_socket);
+    printf (WELCOME_MESSAGE, args.host, args.port, args.host, args.port);
 
-#define BUF_SIZE 1024
+    ttt_server_init (&server);
 
-    while (1) {
-       char buf[BUF_SIZE];
-       int cnt;
-       cnt = read (connected_socket, buf, BUF_SIZE);
-       if (cnt == 0)
-           break;
-       write (0, buf, cnt);
-       write (connected_socket, buf, cnt);
-    }
+    while (1)
+       ttt_socket_accept (socket, _accept_client, &server);
 
-    return 0;
+    /* We only reach here if something bad happened. */
+    return 1;
 }