当前位置:网站首页>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;
}
边栏推荐
- 4. use MySQL shell to install and deploy Mgr clusters | explain Mgr in simple terms
- Cmake tips
- FPGA - 7 Series FPGA selectio -08- oserdese2 of advanced logic resources
- [rust daily] May 24, 2020 rush, rocket, Mun, caspin
- Singleton singleton mode
- Eyebeam advanced settings
- 4~20ma input /0~5v output i/v conversion circuit
- 【网络教程】IPtables官方教程--学习笔记1
- It will cost 700 yuan to realize this issue. Does anyone do it?
- Camx架构开UMD、KMD log以及dump图的方式
猜你喜欢

freeswitch使用mod_shout模块播放mp3

freeswitch设置最大呼叫时长

【网络教程】IPtables官方教程--学习笔记1
![[online tutorial] official iptables tutorial -- learning notes 1](/img/b9/8f94caa46eb46dab581c713494f36d.png)
[online tutorial] official iptables tutorial -- learning notes 1

Online facing such an online world, the only limitation is our imagination

ROS rviz_satellite功能包可视化GNSS轨迹,卫星地图的使用

Linked list (II) - Design linked list

fpm工具安装

VM332 WAService. js:2 Error: _ vm. Changetabs is not a function

Error reporting - resolve core JS / modules / es error. cause. JS error
随机推荐
Compilation principles final review
最后的二十九天
Speech enhancement - spectrum mapping
Wechat applet paging function, pull-down refresh function, direct dry goods
"Jay bear" plummeted by 96.6%. Why is NFT with star goods cold?
Freeswitch使用originate转dialplan
链表(三)——反转链表
MySQL (I) - Installation
JS regular expression system explanation (comprehensive summary)
Freeswitch uses Mod_ Shot module plays mp3
创建格式化时间,格式化时区的gson对象。json解析时间格式化 ZonedDateTime
【Rust翻译】从头实现Rust异步执行器
「杰伦熊」暴跌96.6% 明星带货NFT为何遇冷?
ROS rviz_ Satellite function package visualizes GNSS track and uses satellite map
MySQL(一)——安装
4. use MySQL shell to install and deploy Mgr clusters | explain Mgr in simple terms
Iframe switching in Web Automation
File header information cross reference table
异常处理(一)——空指针和数组索引越界
OpenGL API learning (2008) client server client server