LinuxC/C++编程基础(15) boost同步socket处理
来源:互联网 发布:浪费水资源的数据 编辑:程序博客网 时间:2024/05/16 14:44
一.服务器端server.cpp的实现,如下:
#include <iostream>
#include <boost/asio.hpp>
using namespace boost::asio;
int main(int argc,char** argv){
try{
std::cout<<"serverstart."<<std::endl;
io_service ios;
ip::tcp::acceptor acceptor(ios,ip::tcp::endpoint(ip::tcp::v4(),9999));
std::cout<<acceptor.local_endpoint().address()<<std::endl;
while(true){
ip::tcp::socketsock(ios);
acceptor.accept(sock);
std::cout<<"client:";
std::cout<<sock.remote_endpoint().address()<<std::endl;
sock.write_some(buffer("hello asio"));
}
}catch(std::exception& e){
std::cout<<e.what()<<std::endl;
}
return 0;
}
二.客户端client.cpp的实现,如下:
#include <iostream>
#include <vector>
#include <boost/ref.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost;
using namespace boost::asio;
class a_timer{
private:
int count;
int count_max;
function<void()> f;
deadline_timer t;
public:
template<typename F>
a_timer(io_service& ios,int x,Ffunc):f(func),count_max(x),count(0)
,t(ios,posix_time::millisec(500))
{
t.async_wait(bind(&a_timer::call_func,this,placeholders::error));
}
void call_func(const system::error_code& e){
if(count >= count_max){
return;
}
++count;
f();
t.expires_at(t.expires_at() +posix_time::millisec(500));
t.async_wait(bind(&a_timer::call_func,this,placeholders::error));
}
};
void client(io_service& ios){
try{
std::cout<<"clientstart."<<std::endl;
ip::tcp::socket sock(ios);
ip::tcp::endpointep(ip::address::from_string("127.0.0.1"),9999);
sock.connect(ep);
std::vector<char> str(100,0);
sock.read_some(buffer(str));
std::cout<<"receive from"<<sock.remote_endpoint().address();
std::cout<<""<<&str[0]<<std::endl;
}catch(std::exception& e){
std::cout<<e.what()<<std::endl;
}
}
int main(int argc,char** argv){
io_service ios;
a_timer at(ios,5,bind(client,ref(ios)));
ios.run();
return 0;
}
三.运行结果,如下:
服务器端:
客户端:
参考文献:boost库完全开发指南,罗剑锋 著
转载请注明出处:山水间博客:http://blog.csdn.net/linyanwen99/article/details/8254966
- LinuxC/C++编程基础(15) boost同步socket处理
- LinuxC/C++编程基础(16) boost异步socket处理
- [Boost基础]并发编程——asio网络库——同步socket处理
- linuxc编程一站式学习(c基础)
- LinuxC/C++编程基础(7) boost::mutex的简单实例
- linuxC编程基础
- LinuxC基础编程
- LinuxC/C++编程基础(25) “心跳”信息的处理
- LinuxC/C++编程基础(26) “心跳”信息的处理
- LinuxC/C++编程基础(27) “心跳”信息的处理
- LinuxC/C++编程基础(28) “心跳”信息的处理
- LinuxC/C++编程基础(2) 基于boost::any构建数据容器
- LinuxC/C++编程基础(20) 使用boost::asio搭建服务器简单实例
- LinuxC/C++编程基础(21) 使用boost::asio搭建服务器简单实例(续)
- c#socket编程基础
- c#socket 编程基础
- c#socket编程基础
- C#socket编程基础
- 关于做项目的一些总结
- jsp button onclick事件汇总
- The Coldest Place On Earth——Chapter 6 A Bad Start
- 移植QT4.7.3
- 配置apache2服务器
- LinuxC/C++编程基础(15) boost同步socket处理
- 成绩处理
- Nim Game (博弈论)
- 完全退出程序辅助类(from designer project)
- loadrunner常用函数汇总
- 黑马程序员——银行管理系统
- WinDbg抓取程序报错dump文件的方法
- linux下tools的安装
- 千万要避免的五种程序注释方式