Making a MUD - 2 - A Convenience Function

Go back to part 1

Note: I've tried changing how code is displayed. Hopefully, it will be easier to read.

Rather than creating a character array and calling socket_send with sizeof as a parameter, let's create a function to simplify this.

src/socket_communications.h

 int socket_send (int socket_fd, const char * buffer, size_t buffer_size);
+int socket_send_string (int socket_fd, const char * string);

src/socket_send.c

+int socket_send_string (int socket_fd, const char * string)
+{
+    return socket_send(socket_fd, string, strlen(string));
+}

Of course, by using strlen, we should only use this function for constant strings to prevent possible buffer overruns.

Let's modify start_player_connection to use the new function. While we're at it, let's get a password from the player and go into a command loop.

src/player_login.c

 void * start_player_connection (void * arg)
 {
     struct Player_Connection_Arg * player_connection_arg = arg;
     int socket_fd = player_connection_arg->socket_fd;
     free(player_connection_arg);

-    const char name_prompt [] = "Name: ";
-    send(socket_fd, name_prompt, sizeof(name_prompt) - 1, 0);
+    char name [1024];
+    socket_send_string(socket_fd, "Name: ");
+    socket_receive(socket_fd, name, 1024);

+    char password [1024];
+    socket_send_string(socket_fd, "Password: ");
+    socket_receive(socket_fd, password, 1024);

     socket_send_string(socket_fd, "\nHello, ");
     socket_send_string(socket_fd, name);
     socket_send_string(socket_fd, "!\n\n");

-    char buffer [1024];
-    socket_receive(socket_fd, buffer, 1024);
-    
-    const char disc [] = "Bye!\n";
-    send(socket_fd, disc, sizeof(disc) - 1, 0);

+    for (;;)
+    {
+        socket_send_string(socket_fd, "Command: ");
+        char command [1024];
+        socket_receive(socket_fd, command, 1024);

         if (strncmp(buffer, "shutdown", 8) == 0)
         {

+            socket_send_string(socket_fd, "Goodbye, cruel world!\n\n");

             signal_game_shutdown();
         }

+        else if (strncmp(command, "look", 4) == 0)
+        {
+            socket_send_string(socket_fd, "Maybe one day this will be implemented\n");
+        }
+    }

     close(socket_fd);

     pthread_exit(NULL);
 }

Right now, only the commands shutdown and look are understood. If another command is given, it will be silently ignored.

You can get a copy of this code using subversion:

svn co -r3 http://waronpants.net/mudserver/trunk

Go back to part 1