1 #include <sys/socket.h>
2 #include <netinet/in.h>
13 static struct uloop_fd server;
14 static const char *port = "10000";
15 struct client *next_client = NULL;
18 struct sockaddr_in sin;
24 static void client_read_cb(struct ustream *s, int bytes)
26 struct client *cl = container_of(s, struct client, s.stream);
27 struct ustream_buf *buf = s->r.head;
31 str = ustream_get_read_buf(s, NULL);
35 newline = strchr(buf->data, '\n');
40 ustream_printf(s, "%s\n", str);
41 ustream_consume(s, newline + 1 - str);
42 cl->ctr += newline + 1 - str;
45 if (s->w.data_bytes > 256 && !ustream_read_blocked(s)) {
46 fprintf(stderr, "Block read, bytes: %d\n", s->w.data_bytes);
47 ustream_set_read_blocked(s, true);
51 static void client_close(struct ustream *s)
53 struct client *cl = container_of(s, struct client, s.stream);
55 fprintf(stderr, "Connection closed\n");
61 static void client_notify_write(struct ustream *s, int bytes)
63 fprintf(stderr, "Wrote %d bytes, pending: %d\n", bytes, s->w.data_bytes);
65 if (s->w.data_bytes < 128 && ustream_read_blocked(s)) {
66 fprintf(stderr, "Unblock read\n");
67 ustream_set_read_blocked(s, false);
71 static void client_notify_state(struct ustream *s)
73 struct client *cl = container_of(s, struct client, s.stream);
78 fprintf(stderr, "eof!, pending: %d, total: %d\n", s->w.data_bytes, cl->ctr);
80 return client_close(s);
84 static void server_cb(struct uloop_fd *fd, unsigned int events)
87 unsigned int sl = sizeof(struct sockaddr_in);
91 next_client = calloc(1, sizeof(*next_client));
94 sfd = accept(server.fd, (struct sockaddr *) &cl->sin, &sl);
96 fprintf(stderr, "Accept failed\n");
100 cl->s.stream.string_data = true;
101 cl->s.stream.notify_read = client_read_cb;
102 cl->s.stream.notify_state = client_notify_state;
103 cl->s.stream.notify_write = client_notify_write;
104 ustream_fd_init(&cl->s, sfd);
106 fprintf(stderr, "New connection\n");
109 static int run_server(void)
112 server.cb = server_cb;
113 server.fd = usock(USOCK_TCP | USOCK_SERVER | USOCK_IPV4ONLY | USOCK_NUMERIC, "127.0.0.1", port);
120 uloop_fd_add(&server, ULOOP_READ);
126 static int usage(const char *name)
128 fprintf(stderr, "Usage: %s -p <port>\n", name);
132 int main(int argc, char **argv)
136 while ((ch = getopt(argc, argv, "p:")) != -1) {
142 return usage(argv[0]);