project skeleton
This commit is contained in:
commit
d9ee2c56f2
8 changed files with 237 additions and 0 deletions
80
main.c
Normal file
80
main.c
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
#define _GNU_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <uv.h>
|
||||
#include <pthread.h>
|
||||
#include "client.h"
|
||||
|
||||
uv_loop_t *loop;
|
||||
|
||||
void alloc_buffer(uv_handle_t *handle, size_t suggested_size, uv_buf_t *buf)
|
||||
{
|
||||
(void)handle;
|
||||
buf->base = (char*) malloc(suggested_size);
|
||||
buf->len = suggested_size;
|
||||
}
|
||||
|
||||
void echo_write(uv_write_t *req, int status)
|
||||
{
|
||||
if (status) {
|
||||
fprintf(stderr, "Write error %s\n", uv_strerror(status));
|
||||
}
|
||||
free(req);
|
||||
}
|
||||
|
||||
void on_close(uv_handle_t *handle)
|
||||
{
|
||||
free(handle);
|
||||
}
|
||||
|
||||
void on_read(uv_stream_t *client, ssize_t nread, const uv_buf_t *buf)
|
||||
{
|
||||
if (nread > 0) {
|
||||
uv_write_t *req = (uv_write_t *) malloc(sizeof(uv_write_t));
|
||||
uv_buf_t wrbuf = uv_buf_init(buf->base, nread);
|
||||
uv_write(req, client, &wrbuf, 1, echo_write);
|
||||
}
|
||||
if (nread < 0) {
|
||||
if (nread != UV_EOF)
|
||||
fprintf(stderr, "Read error %s\n", uv_err_name(nread));
|
||||
uv_close((uv_handle_t*) client, on_close);
|
||||
}
|
||||
free(buf->base);
|
||||
}
|
||||
|
||||
void on_new_connection(uv_stream_t *server, int status)
|
||||
{
|
||||
if (status < 0) {
|
||||
fprintf(stderr, "New connection error %s\n", uv_strerror(status));
|
||||
return;
|
||||
}
|
||||
|
||||
struct client *client = malloc(sizeof(struct client));
|
||||
uv_tcp_init(loop, &client->handle);
|
||||
if (uv_accept(server, (uv_stream_t*) &client->handle) == 0) {
|
||||
uv_read_start((uv_stream_t*) &client->handle, alloc_buffer, on_read);
|
||||
} else {
|
||||
uv_close((uv_handle_t*) &client->handle, on_close);
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
loop = uv_default_loop();
|
||||
|
||||
uv_tcp_t server;
|
||||
uv_tcp_init(loop, &server);
|
||||
|
||||
struct sockaddr_in addr;
|
||||
uv_ip4_addr("0.0.0.0", 7000, &addr);
|
||||
|
||||
uv_tcp_bind(&server, (const struct sockaddr*)&addr, 0);
|
||||
int r = uv_listen((uv_stream_t*) &server, 128, on_new_connection);
|
||||
|
||||
if (r) {
|
||||
fprintf(stderr, "Listen error %s\n", uv_strerror(r));
|
||||
return 1;
|
||||
}
|
||||
return uv_run(loop, UV_RUN_DEFAULT);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue