学习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