当前位置:网站首页>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;
}
边栏推荐
- [rust translation] implement rust asynchronous actuator from scratch
- fpm工具安装
- Linked list (II) - Design linked list
- Interpretation of Blog
- Puge -- singleton mode
- 链表(一)——移除链表元素
- Techo day Tencent technology open day, June 28 online waiting for you!
- 职场IT老鸟的几点小习惯
- Integer promotion and size side byte order
- FPGA - 7系列 FPGA SelectIO -08- 高级逻辑资源之OSERDESE2
猜你喜欢

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

pytorch RNN 学习笔记

Build your jmeter+jenkins+ant

Yolov5 adds a small target detection layer

浮动与定位

js正则表达式系统讲解(全面的总结)

eyebeam高级设置

Niubi 666, this project makes web page making as simple as building blocks
![[c #] [reprint]furion frame address and tutorial address](/img/b2/e1c30153c4237188b60e9523b0a5d8.png)
[c #] [reprint]furion frame address and tutorial address

Freeswitch uses Mod_ Shot module plays mp3
随机推荐
Rust FFI programming - libc crate
It will cost 700 yuan to realize this issue. Does anyone do it?
普歌--三大基础排序,冒泡·选择·快速
推荐10个好用到爆的Jupyter Notebook插件,让你效率飞起
助力涨点 | YOLOv5结合Alpha-IoU
创建格式化时间,格式化时区的gson对象。json解析时间格式化 ZonedDateTime
[interval DP] stone consolidation
【Paper Reading-3D Detection】Fully Convolutional One-Stage 3D Object Detection on LiDAR Range Images
CMAKE小知识
Last 29 days
Overview, implementation and use of CRC32
选拔赛题目代码
链表(三)——反转链表
2 startup, interrupt and system call
Uni app wechat applet sharing function
MySQL (II) - basic operation
The code is correct, and the rendering page does not display the reason
小程序页面设置100%高度还是留白怎么办?
JS regular expression system explanation (comprehensive summary)
Triode driven brushless motor