基于libuv的TCP echo-server

这篇博客介绍了如何利用libuv库构建一个TCP echo-server。作者参考了libuv源码中的test/echo-server.c文件,并添加了自己的代码,使得服务器在接收到客户端的奇数次输入时原样返回,偶数次则返回输入文字的逆序。通过这个例子,读者可以学习到如何在异步非阻塞模式下,使用libuv进行socket编程,包括创建socket、bind、listen、accept等步骤,以及如何注册连接回调、读写函数。
摘要由CSDN通过智能技术生成

学习libuv库,写TCP echo-server

大部分代码都来自libuv源码test目录下echo-server.c文件。

我自己添加了一点代码,通过uv_read_start函数更改read_cb函数

使得第奇数次客户端输入一行文字后,服务端原样返回,

偶数次输入一行文字,服务端将输入的一行文字逆序后返回

结果如下:

cheng@debian:~$ telnet 127.0.0.1 7890
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
helo
helo
helo
oleh
00000111111
00000111111
00000111111
11111100000


---------------------------------------------------------总结的分割线---------------------------------------------------------------------------------

通过echo-server这个程序,可以学习怎么利用libuv,像完成原始socket网络编程那样,

创建socket, bind, listen, accept过程。

只是在异步,非阻塞的方式编程时,需要通过事先为某个事件发生时应该调用的回调

在echo-server程序中,通过uv_listen函数注册连接回调函数

uv_read_start注册读函数

uv_write注册写函数

在头文件uv.h看这三个函数的函数原型,可以很清楚的知道每个参数的意义

------------------------------------------------------------------------------------------------------------------------------------------------------------

修改过的echo-server.c代码:

/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO T
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值