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

103 lines
1.8 KiB
C
Raw Normal View History

2011-03-28 01:55:29 -07:00
#include "../ol.h"
#include <stdio.h>
2011-03-28 03:26:00 -07:00
#include <stdlib.h>
2011-03-28 03:54:18 -07:00
#include <assert.h>
2011-03-28 01:55:29 -07:00
2011-03-28 03:17:52 -07:00
#define BUFSIZE 1024
2011-03-28 01:55:29 -07:00
typedef struct {
ol_handle* handle;
2011-03-28 01:55:29 -07:00
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;
2011-03-31 14:22:20 +02:00
void after_write(ol_req* req);
void after_read(ol_req* req, size_t nread);
2011-03-28 01:55:29 -07:00
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);
2011-03-31 14:22:20 +02:00
void after_write(ol_req* req) {
peer_t *peer = (peer_t*) req->data;
try_read(peer);
2011-03-28 01:55:29 -07:00
}
2011-03-31 14:22:20 +02:00
void after_read(ol_req* req, size_t nread) {
if (nread == 0) {
ol_close(req->handle);
} else {
peer_t *peer = (peer_t*) req->data;
peer->buf.len = nread;
peer->req.cb = after_write;
ol_write(peer->handle, &peer->req, &peer->buf, 1);
2011-03-28 01:55:29 -07:00
}
}
void try_read(peer_t* peer) {
peer->buf.len = BUFSIZE;
2011-03-29 16:40:27 -07:00
peer->req.cb = after_read;
2011-03-28 01:55:29 -07:00
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-30 01:34:56 +02:00
peer_t* p;
int r;
2011-03-28 01:55:29 -07:00
new_client->close_cb = on_close;
p = (peer_t*)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-31 14:22:20 +02:00
ol_req_init(&p->req, NULL);
2011-03-28 01:55:29 -07:00
2011-03-28 03:17:52 -07:00
try_read(p);
2011-03-28 01:55:29 -07:00
2011-03-30 01:34:56 +02:00
r = ol_write2(new_client, "Hello\n");
2011-03-28 01:55:29 -07:00
if (r < 0) {
2011-03-29 16:40:27 -07:00
/* error */
2011-03-28 01:55:29 -07:00
assert(0);
}
}
int echo_start(int port) {
ol_handle* server = ol_tcp_handle_new(on_close, NULL);
2011-03-29 10:08:45 -07:00
struct sockaddr_in addr = ol_ip4_addr("0.0.0.0", port);
2011-03-28 01:55:29 -07:00
int r = ol_bind(server, (struct sockaddr*) &addr);
2011-03-29 10:08:45 -07:00
if (r) {
/* TODO: Error codes */
2011-03-29 10:08:45 -07:00
fprintf(stderr, "Bind error\n");
return 1;
}
r = ol_listen(server, 128, on_accept);
if (r) {
/* TODO: Error codes */
2011-03-29 10:08:45 -07:00
fprintf(stderr, "Listen error\n");
return 1;
}
2011-03-28 01:55:29 -07:00
return 0;
}