1
0
mirror of https://github.com/libuv/libuv synced 2025-03-28 21:13:16 +00:00
libuv/test/echo-server.c

92 lines
1.7 KiB
C
Raw Normal View History

2011-03-28 01:55:29 -07:00
#include "../ol.h"
#include <stdio.h>
2011-03-28 03:17:52 -07:00
#define BUFSIZE 1024
2011-03-28 01:55:29 -07:00
typedef struct {
ol_handle *handle;
ol_req req;
ol_buf buf;
2011-03-28 03:17:52 -07:00
char read_buffer[BUFSIZE];
2011-03-28 01:55:29 -07:00
} peer_t;
void after_write(ol_req* req, ol_err err);
void after_read(ol_req* req, size_t nread, ol_err err);
void try_read(peer_t* peer);
void on_close(ol_handle* peer, ol_err err);
void on_accept(ol_handle* server, ol_handle* new_client);
void after_write(ol_req* req, ol_err err) {
if (!err) {
peer_t *peer = (peer_t*) req->data;
try_read(peer);
}
}
void after_read(ol_req* req, size_t nread, ol_err err) {
if (!err) {
if (nread == 0) {
ol_close(req->handle);
} else {
peer_t *peer = (peer_t*) req->data;
peer->buf.len = nread;
peer->req.write_cb = after_write;
ol_write(peer->handle, &peer->req, &peer->buf, 1);
}
}
}
void try_read(peer_t* peer) {
peer->buf.len = BUFSIZE;
peer->req.read_cb = after_read;
ol_read(peer->handle, &peer->req, &peer->buf, 1);
}
void on_close(ol_handle* peer, ol_err err) {
if (err) {
2011-03-28 03:17:52 -07:00
fprintf(stdout, "Socket error\n");
2011-03-28 01:55:29 -07:00
}
ol_free(peer);
}
2011-03-28 03:17:52 -07:00
void on_accept(ol_handle* server, ol_handle* new_client) {
2011-03-28 01:55:29 -07:00
new_client->close_cb = on_close;
2011-03-28 03:17:52 -07:00
peer_t* p = malloc(sizeof(peer_t));
2011-03-28 01:55:29 -07:00
p->handle = new_client;
p->buf.base = p->read_buffer;
p->buf.len = BUFSIZE;
p->req.data = p;
2011-03-28 03:17:52 -07:00
try_read(p);
2011-03-28 01:55:29 -07:00
2011-03-28 03:17:52 -07:00
int r = ol_write2(new_client, "Hello\n");
2011-03-28 01:55:29 -07:00
if (r < 0) {
// error
assert(0);
}
}
int main(int argc, char** argv) {
2011-03-28 03:17:52 -07:00
ol_handle* server = ol_handle_new(on_close, NULL);
2011-03-28 01:55:29 -07:00
2011-03-28 03:17:52 -07:00
struct sockaddr_in addr = ol_ip4_addr("0.0.0.0", 8000);
ol_bind(server, (struct sockaddr*) &addr);
2011-03-28 01:55:29 -07:00
ol_listen(server, 128, on_accept);
ol_run();
return 0;
}