1 #include <sys/socket.h>
2 #include <netinet/in.h>
14 static struct uloop_fd server
;
15 static const char *port
= "10000";
16 struct client
*next_client
= NULL
;
19 struct sockaddr_in sin
;
25 static void client_read_cb(struct ustream
*s
, int bytes
)
27 struct client
*cl
= container_of(s
, struct client
, s
.stream
);
28 struct ustream_buf
*buf
= s
->r
.head
;
32 str
= ustream_get_read_buf(s
, NULL
);
36 newline
= strchr(buf
->data
, '\n');
41 ustream_printf(s
, "%s\n", str
);
42 ustream_consume(s
, newline
+ 1 - str
);
43 cl
->ctr
+= newline
+ 1 - str
;
46 if (s
->w
.data_bytes
> 256 && !ustream_read_blocked(s
)) {
47 fprintf(stderr
, "Block read, bytes: %d\n", s
->w
.data_bytes
);
48 ustream_set_read_blocked(s
, true);
52 static void client_close(struct ustream
*s
)
54 struct client
*cl
= container_of(s
, struct client
, s
.stream
);
56 fprintf(stderr
, "Connection closed\n");
62 static void client_notify_write(struct ustream
*s
, int bytes
)
64 fprintf(stderr
, "Wrote %d bytes, pending: %d\n", bytes
, s
->w
.data_bytes
);
66 if (s
->w
.data_bytes
< 128 && ustream_read_blocked(s
)) {
67 fprintf(stderr
, "Unblock read\n");
68 ustream_set_read_blocked(s
, false);
72 static void client_notify_state(struct ustream
*s
)
74 struct client
*cl
= container_of(s
, struct client
, s
.stream
);
79 fprintf(stderr
, "eof!, pending: %d, total: %d\n", s
->w
.data_bytes
, cl
->ctr
);
81 return client_close(s
);
85 static void server_cb(struct uloop_fd
*fd
, unsigned int events
)
88 unsigned int sl
= sizeof(struct sockaddr_in
);
92 next_client
= calloc(1, sizeof(*next_client
));
95 sfd
= accept(server
.fd
, (struct sockaddr
*) &cl
->sin
, &sl
);
97 fprintf(stderr
, "Accept failed\n");
101 cl
->s
.stream
.string_data
= true;
102 cl
->s
.stream
.notify_read
= client_read_cb
;
103 cl
->s
.stream
.notify_state
= client_notify_state
;
104 cl
->s
.stream
.notify_write
= client_notify_write
;
105 ustream_fd_init(&cl
->s
, sfd
);
107 fprintf(stderr
, "New connection\n");
110 static int run_server(void)
113 server
.cb
= server_cb
;
114 server
.fd
= usock(USOCK_TCP
| USOCK_SERVER
| USOCK_IPV4ONLY
| USOCK_NUMERIC
, "127.0.0.1", port
);
121 uloop_fd_add(&server
, ULOOP_READ
);
127 static int usage(const char *name
)
129 fprintf(stderr
, "Usage: %s -p <port>\n", name
);
133 int main(int argc
, char **argv
)
137 while ((ch
= getopt(argc
, argv
, "p:")) != -1) {
143 return usage(argv
[0]);