*/
#include "ttt.h"
+#include "ttt-socket.h"
+
+static void
+ttt_dispatch (int connected_socket)
+{
+#define BUF_SIZE 1024
+
+ 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);
+ }
+}
+
+static const char *WELCOME_MESSAGE =
+"Welcome to ttt-server. So far, this program is simply a demonstration\n"
+"of a TCP/IP server that handles one client at a time. The server is\n"
+"currently listening on:\n"
+"\n %s:%s\n"
+"\nTo test this program, simply connect a client 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"
+"\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. The server handles only one client at a time, but multiple clients\n"
+"may be able to connect simultaneously. Subsequent clients will see no\n"
+"output from the server until all previous clients exit.\n"
+"\nExtending the server to fork a new process for each client would be a fun\n"
+"project for a motivated student (as would writing a custom client program).\n\n";
int
main (int argc, char **argv)
{
ttt_args_t args;
- int args_first;
+ int socket;
+
+ ttt_args_parse (&args, argc, argv);
+
+ if (args.log_file)
+ stderr = xfreopen (args.log_file, "a", stderr);
+
+ socket = ttt_socket_create_server (args.host, args.port);
- ttt_args_parse (&args, argc, argv, &args_first);
+ printf (WELCOME_MESSAGE, args.host, args.port, args.host, args.port);
- /* XXX: insert code here */
+ while (1)
+ ttt_socket_accept (socket, ttt_dispatch);
- return 0;
+ /* We only reach here if something bad happened. */
+ return 1;
}