]> git.pond.sub.org Git - empserver/blob - src/lib/lwp/misc/echo.c
Indented with src/scripts/indent-emp.
[empserver] / src / lib / lwp / misc / echo.c
1 /* 
2  * server.c
3  *
4  * lwp (echo) connection handler server
5  *
6  */
7
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <sys/types.h>
11 #include <sys/time.h>
12 #include <sys/socket.h>
13 #include <netinet/in.h>
14
15 #define SP_ACCEPT       3
16 #define SP_READER       3
17
18 #include "lwp.h"
19
20 struct context {
21     struct lwpProc *us;
22     struct sockaddr_in addr;
23     int fd;
24 };
25
26 /*ARGSUSED*/
27 int
28 readConn(argc, argv, ud)
29 int argc;
30 char **argv;
31 void *ud;
32 {
33     struct context *ctx = (struct context *)ud;
34     char buf[1024];
35     int n;
36
37     while (1) {
38         printf("sleeping\n");
39         lwpSleepFd(ctx->fd, LWP_FD_READ);
40         printf("waiting to read\n");
41         if ((n = read(ctx->fd, buf, sizeof(buf))) <= 0)
42             break;
43         printf("got %d char\n", n);
44         lwpSleepFd(ctx->fd, LWP_FD_WRITE);
45         printf("waiting to write\n");
46         if (write(ctx->fd, buf, n) < 0)
47             break;
48         printf("wrote %d char\n", n);
49     }
50     printf("process/fd %d exiting\n", ctx->fd);
51     close(ctx->fd);
52     lwpExit();
53     /*NOTREACHED*/
54 }
55
56 int
57 acceptConn(argc, argv)
58 int argc;
59 char **argv;
60 {
61     struct sockaddr_in sin;
62     int s;
63     int ns;
64     int len;
65     int maxfd;
66     struct context *ctx;
67
68     if (argc != 2) {
69         fprintf(stderr, "Usage: %s port\n", *argv);
70         exit(-1);
71     }
72     if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
73         perror("inet socket");
74         exit(-1);
75     }
76     sin.sin_family = AF_INET;
77     sin.sin_port = htons(atoi(argv[1]));
78     sin.sin_addr.s_addr = 0;
79     if (bind(s, &sin, sizeof(sin)) < 0) {
80         perror("inet socket bind");
81         exit(-1);
82     }
83     if (listen(s, LISTENMAXCONN) < 0) {
84         perror("inet socket listen");
85         exit(-1);
86     }
87     maxfd = getdtablesize() - 1;
88     while (1) {
89         lwpSleepFd(s, LWP_FD_READ);
90         len = sizeof(sin);
91         ns = accept(s, &sin, &len);
92         if (ns < 0) {
93             perror("accept");
94             exit(-1);
95         }
96         if (ns == maxfd) {
97             fprintf(stderr, "no more connections");
98             close(ns);
99         }
100         printf("got connection from %s\n", inet_ntoa(sin.sin_addr));
101         ctx = (struct context *)malloc(sizeof(*ctx));
102         ctx->addr = sin;
103         ctx->fd = ns;
104         ctx->us = lwpCreate(SP_READER, readConn, 8192, 0, 0, ctx);
105     }
106     /*NOTREACHED*/
107 }
108
109 int
110 main(argc, argv)
111 int argc;
112 char **argv;
113 {
114     lwpInitSystem(1);
115     lwpCreate(SP_ACCEPT, acceptConn, 8192, argc, argv, 0);
116     lwpReschedule();
117     /*NOTREACHED*/
118 }