当前位置:网站首页>Libuv framework echo server C source code explanation (TCP part)
Libuv framework echo server C source code explanation (TCP part)
2022-06-28 06:53:00 【ufgnix0802】
Libuv frame echo-server.c Source details (TCP part )
echo-server.c File is Libuv Entry level examples in the framework , Provided by the government . About echo-server.c How to find documents , You can refer to the link :https://blog.csdn.net/qq135595696/article/details/125475334?spm=1001.2014.3001.5501
Effect display
Client side usage sokit Tools to demonstrate .

function Libuv Framework of the echo-server.c file , The effect is as follows :

Source code
main.c( About Libuv You can also refer to the link at the beginning of the article for environment construction )
#include "uv.h"
#include "task.h"
#include <stdio.h>
#include <stdlib.h>
static uv_loop_t* loop;// Event cycle mechanism
static uv_handle_t* server;// Server handle
static uv_tcp_t tcpServer;//TCP Server handle structure
static stream_type serverType;// Service type of the server
// Send buffer
typedef struct
{
uv_write_t req;
uv_buf_t buf;
}write_req_t;
static void uv_close(uv_handle_t* peer)
{
free(peer);
}
// Callback response event after closing the current client
static void after_shutdown(uv_shutdown_t* req, int status)
{
ASSERT_EQ(status, 0);
uv_close((uv_handle_t*)req->handle, uv_close);
free(req);
}
// Callback event after sending a message to the client
static void after_write(uv_write_t* req, int status)
{
write_req_t* wr;
/*Free the read/write buffer and the request*/
wr = (write_req_t*)req;
free(wr->buf.base);
free(wr);
if (status == 0)
return;
fprintf(stderr, "uv_write error:%s - %s\n",
uv_err_name(status),
uv_strerror(status));
}
// Open buffer size
static void echo_alloc(uv_handle_t* handle,
size_t suggested_size,
uv_buf_t* buf)
{
buf->base = malloc(suggested_size);
buf->len = suggested_size;
}
// Response event after receiving client data
static void after_read(uv_stream_t* handle,
ssize_t nread,// Length of data read
const uv_buf_t* buf)
{
// Close client events
uv_shutdown_t* sreq;
// Write events
write_req_t* wr;
// Failed to read data
if (nread < 0)
{
/*Error or EOF*/
ASSERT_EQ(nread, UV_EOF);
free(buf->base);
sreq = malloc(sizeof * sreq);
// Check whether the current client is writable
if (uv_is_writable(handle))
{
// Close the current client , And register the response callback event after closing the current client
ASSERT_EQ(0, uv_shutdown(sreq, handle, after_shutdown));
}
return;
}
// No readable messages
if (nread == 0)
{
/*Everything OK,but nothing read.*/
free(buf->base);
return;
}
// Processing client messages
wr = (write_req_t*)malloc(sizeof * wr);
ASSERT_NOT_NULL(wr);
// Initialize send buffer
wr->buf = uv_buf_init(buf->base, nread);
// Send a message to the client , And register the callback event after sending the message
if (uv_write(&wr->req, handle, &wr->buf, 1, after_write))
{
FATAL("uv_write failed");
}
}
// The response callback function for the arrival of the client connection
static void on_connection(uv_stream_t* server, int status)
{
uv_stream_t* stream;
int r;
if (status != 0)
fprintf(stderr, "Connect error %s\n", uv_err_name(status));
ASSERT(status == 0);
switch (serverType)
{
case TCP:
stream = malloc(sizeof(uv_tcp_t));// Create a stream to manage the currently received client
ASSERT_NOT_NULL(stream);
r = uv_tcp_init(loop, (uv_tcp_t*)stream);// Link the client to the current loop( Event cycle mechanism ) relation
ASSERT(r == 0);
break;
default:
ASSERT(0 && "Bad serverType");
abort();
}
/* associate server with stream, Associate the client with the current server */
stream->data = server;
r = uv_accept(server, stream);// Receive incoming clients
ASSERT(r == 0);
// Receive messages from clients , And register the callback response event after receiving the client message and the callback event for allocating the receiving buffer size
r = uv_read_start(stream, echo_alloc, after_read);
ASSERT(r == 0);
}
static int tcp4_echo_start(int port)
{
struct sockaddr_in addr;
int r;
// If you follow 0 equal , Then continue
// Set up IP Address and port number
ASSERT(0 == uv_ip4_addr("127.0.0.1", port, &addr));
server = (uv_handle_t*)&tcpServer;
serverType = TCP;
r = uv_tcp_init(loop, &tcpServer);// Initialize and create socket
if (r)
{
/* TODO:Error codes*/
fprintf(stderr, "Socket creation error\n");
return 1;
}
r = uv_tcp_bind(&tcpServer, (const struct sockaddr*)&addr, 0);// hold socket Follow IP Binding with port number
if (r)
{
/*TODO:Error codes*/
fprintf(stderr, "Bind error\n");
return 1;
}
r = uv_listen((uv_stream_t*)&tcpServer, SOMAXCONN, on_connection);// Listening port , Receive the client connection and register the response callback event after the client arrives
if (r)
{
/*TODO:Error codes*/
fprintf(stderr, "Listen error %s\n", uv_err_name(r));
return 1;
}
return 0;
}
int main()
{
loop = uv_default_loop();// Initialize the event loop mechanism
// Create server
if (tcp4_echo_start(TEST_PORT))
return 1;
// Start the event loop mechanism
uv_run(loop, UV_RUN_DEFAULT);
return 0;
}
边栏推荐
- Iframe switching in Web Automation
- 整型提昇和大小端字節序
- 声网 VQA:将实时互动中未知的视频画质用户主观体验变可知
- C language tutorial
- Last 29 days
- 5-minute NLP: summary of time chronology from bag of words to transformer
- FPGA - 7 Series FPGA selectio -07- iserdese2 of advanced logic resources
- Some habits of it veterans in the workplace
- Recommend several 0 code, free, learning and using visualization tools
- Eyebeam advanced settings
猜你喜欢

整型提升和大小端字节序

Libuv框架echo-server.c源码详解(TCP部分)

推荐几款0代码、免费、现学现用的可视化工具

【Paper Reading-3D Detection】Fully Convolutional One-Stage 3D Object Detection on LiDAR Range Images

Linked list (I) - remove linked list elements

我的MVVM开源项目《出行防疫App》已发布

Exception handling (I) -- null pointer and array index out of bounds

Freeswitch sets the maximum call duration

pytorch RNN 学习笔记

FPGA - 7系列 FPGA SelectIO -09- 高级逻辑资源之IO_FIFO
随机推荐
[rust daily] May 24, 2020 rush, rocket, Mun, caspin
Linux Mysql 实现root用户不用密码登录
Freeswitch uses origin to dialplan
[C#][转载]furion框架地址和教程地址
Linux MySQL implements root user login without password
Integer promotion and size side byte order
[digital statistics DP] counting problem
Deleting MySQL under Linux
ImportError: cannot import name 'ensure_ dir_ Possible solutions for exists'
[rust translation] implement rust asynchronous actuator from scratch
【Rust日报】2020-05-24 Rash, Rocket, Mun, Casbin
【Paper Reading-3D Detection】Fully Convolutional One-Stage 3D Object Detection on LiDAR Range Images
JDBC learning (I) -- implementing simple CRUD operations
[staff] arpeggio mark
UPC -- expression evaluation
@RequestParam
Rust FFI programming - libc crate
Drop down list processing in Web Automation
Call interface event API common event methods
ROS rviz_satellite功能包可视化GNSS轨迹,卫星地图的使用