博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
boot asio 非阻塞同步编程---非阻塞的accept和receive。
阅读量:4045 次
发布时间:2019-05-24

本文共 2480 字,大约阅读时间需要 8 分钟。

boot asio 非阻塞同步编程---非阻塞的accept和receive。

2014年4月11日15:45:19

客户端编程:

#include
#include
#include
#include
using namespace boost::asio;using namespace std;#define RECEIVE_BUF_SIZE 100#define RECEIVE_BYTE_NUM 30int readMaxBytesInTime(ip::tcp::socket & socket,char * strBuf,int nMaxBytes,int nMilSec){ boost::timer t; int nTotalRec = 0; int nLeftBytes = nMaxBytes - nTotalRec; while(1) { boost::system::error_code ec; char buf[RECEIVE_BUF_SIZE]; int nWantBytes = 0; if(nLeftBytes < RECEIVE_BUF_SIZE) { nWantBytes = nLeftBytes; } else { nWantBytes = RECEIVE_BUF_SIZE; } size_t len=socket.read_some(buffer(buf,nWantBytes), ec); if(len>0) { memcpy(strBuf + nTotalRec,buf,len); nTotalRec += len; nLeftBytes -= len; if(nLeftBytes <= 0) break; else continue; } else { if(t.elapsed()*1000 < nMilSec) { Sleep(0); continue; } else break; } } return nTotalRec;}int main(int argc, char* argv[]){ // 所有asio类都需要io_service对象 io_service iosev; // socket对象 ip::tcp::socket socket(iosev); socket.open(boost::asio::ip::tcp::v4()); socket.io_control(boost::asio::ip::tcp::socket::non_blocking_io(true)); // 连接端点,这里使用了本机连接,可以修改IP地址测试远程连接 ip::tcp::endpoint ep(ip::address_v4::from_string("127.0.0.1"), 1000); // 连接服务器 boost::system::error_code ec; boost::timer t; socket.connect(ep,ec); cout<< t.elapsed()<<"s"<

服务器端编程:

#include 
#include
#include
int main(int argc, char* argv[]){ using namespace boost::asio; // 所有asio类都需要io_service对象 io_service iosev; ip::tcp::acceptor acceptor(iosev); acceptor.open(boost::asio::ip::tcp::v4()); acceptor.io_control(boost::asio::ip::tcp::socket::non_blocking_io(true)); // 连接端点,这里使用了本机连接,可以修改IP地址测试远程连接 ip::tcp::endpoint ep(ip::address_v4::from_string("127.0.0.1"), 1000); acceptor.bind(ep); acceptor.listen(); for(;;) { boost::system::error_code ec; // socket对象 ip::tcp::socket socket(iosev); // 等待直到客户端连接进来 while (1) { acceptor.accept(socket,ec); if(ec) { std::cout << boost::system::system_error(ec).what() << std::endl; Sleep(10); } else break; } system("PAUSE"); // 显示连接进来的客户端 std::cout << socket.remote_endpoint().address() << std::endl; // 向客户端发送hello world! char * str = "hello world!hello world!"; socket.write_some(buffer(str,20), ec); // 如果出错,打印出错信息 if(ec) { std::cout << boost::system::system_error(ec).what() << std::endl; break; } // 与当前客户交互完成后循环继续等待下一客户连接 } return 0;}

转载地址:http://jnwci.baihongyu.com/

你可能感兴趣的文章
linux不同模块completion通信
查看>>
linux printf获得时间戳
查看>>
C语言位扩展
查看>>
linux irqdebug
查看>>
git 常用命令
查看>>
linux位操作API
查看>>
uboot.lds文件分析
查看>>
uboot start.s文件分析
查看>>
没有路由器的情况下,开发板,虚拟机Ubuntu,win10主机,三者也可以ping通
查看>>
本地服务方式搭建etcd集群
查看>>
安装k8s Master高可用集群
查看>>
忽略图片透明区域的事件(Flex)
查看>>
忽略图片透明区域的事件(Flex)
查看>>
AS3 Flex基础知识100条
查看>>
Flex动态获取flash资源库文件
查看>>
flex4 中创建自定义弹出窗口
查看>>
01Java基础语法-16. while循环结构
查看>>
01Java基础语法-18. 各种循环语句的区别和应用场景
查看>>
01Java基础语法-19. 循环跳转控制语句
查看>>
Django框架全面讲解 -- Form
查看>>