当前位置:网站首页>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;
}
边栏推荐
- FPGA - 7系列 FPGA SelectIO -07- 高级逻辑资源之ISERDESE2
- It will cost 700 yuan to realize this issue. Does anyone do it?
- MySQL(一)——安装
- Iframe switching in Web Automation
- VM332 WAService.js:2 Error: _vm.changeTabs is not a function报错
- 调接口事件API常用事件方法
- 链表(三)——反转链表
- ImportError: cannot import name 'ensure_ dir_ Possible solutions for exists'
- Note that JPA uses a custom VO to receive jpql query results
- 编译原理期末复习
猜你喜欢
![[staff] arpeggio mark](/img/45/0ee0089b947b467344b247839893d7.jpg)
[staff] arpeggio mark

Freeswitch uses Mod_ Shot module plays mp3

Techo day Tencent technology open day, June 28 online waiting for you!

Recommend several 0 code, free, learning and using visualization tools

Compile configuration in file

Linux Mysql 实现root用户不用密码登录

MySQL (I) - Installation

VM332 WAService.js:2 Error: _vm.changeTabs is not a function报错

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

Iframe switching in Web Automation
随机推荐
Integer promotion and size side byte order
pytorch RNN 学习笔记
"Jay bear" plummeted by 96.6%. Why is NFT with star goods cold?
Techo day Tencent technology open day, June 28 online waiting for you!
[rust daily] published on rust 1.43.0 on April 23, 2020
编译原理期末复习
MySQL(一)——安装
JS regular expression system explanation (comprehensive summary)
[rust daily] May 24, 2020 rush, rocket, Mun, caspin
记JPA使用自定义VO接收 JPQL查询结果
异常处理(一)——空指针和数组索引越界
Puge -- singleton mode
YOLOv5增加小目标检测层
Linked list (II) - Design linked list
Batch import of pictures into WPS table by date
微信小程序分页功能,下拉刷新功能,直接干货拿来就用
语音增强-频谱映射
ImportError: cannot import name 'ensure_ dir_ Possible solutions for exists'
VM332 WAService.js:2 Error: _vm.changeTabs is not a function报错
CAD secondary development +nettopologysuite+pgis reference multi version DLL