异步服务器端

#include <conio.h>
#include <iostream>
using namespace std;
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
using namespace boost;
using namespace boost::asio;
void test1(){}
//异步server
//异步程序的处理流程与同步程序基本相同,只需要把原有的同步调用函数都换成前缀是async_的异步调用函数,并增加回调函数,在回调函数中再启动一个异步调用。
class server
{
private:
io_service& ios;
ip::tcp::acceptor acceptor;
typedef shared_ptr<ip::tcp::socket> sock_pt;
public:
server(io_service& io):ios(io),acceptor(ios,ip::tcp::endpoint(ip::tcp::v4(),6688))
{
start();
}
void start()
{
sock_pt sock(new ip::tcp::socket(ios));//智能指针
acceptor.async_accept(*sock,bind(&server::accept_handler,this,placeholders::error,sock));//异步监听服务
//start()函数用于启动异步接受连接,需要调用acceptor的async_accept()函数。为了能够让socket镀锡能够被异步调用后还能使用,我们必须使用shared_ptr来创建socket对象的智能指针,它可以再程序的整个生命周期中存在,直到没有人使用它为止。
}
//当有TCP连接发生时,server::accept_handler()函数将被调用,它使用socket对象发生数据。
void accept_handler(const system::error_code& ec,sock_pt sock)
{
if (ec)//检测错误码
{
return;
}
cout<<"client:";//输出连接的客户端信息
cout<<sock->remote_endpoint().address()<<" port:"<<sock->remote_endpoint().port()<<endl;
sock->async_write_some(buffer("hello asio"),bind(&server::write_handler,this,placeholders::error));
start();//再次启动异步接受连接
//首先它必须检测asio传递的error_code,保证没有错误发生。然后调用socket对象的async_write_some()异步发生数据。同样,我们必须再为这个异步调用编写回调函数write_handler()。当发生完数据后不要忘了调用start()再次启动服务器接收连接,否则当完成数据发送后io_service将因为没有时间处理而结束运行。
}
void write_handler(const system::error_code&)
{
cout<<"send msg complete."<<endl;
}
};
void test2()
{
try
{
cout<<"server start."<<endl;
io_service ios;
server serv(ios);
ios.run();
}
catch (std::exception& e)
{
cout<<e.what()<<endl;
}
}
void test(char t)
{
std::cout<<"press key====="<<t<<std::endl;
switch (t)
{
case '1':test1();break;
case '2':test2();break;
case 27:
case 'q':exit(0);break;
default: std::cout<<"default "<<t<<std::endl;break;
}
}
void main()
{
while (1)
{
test(getch());
}
}

异步客户端

#include <conio.h>
#include <iostream>
using namespace std;
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost;
using namespace boost::asio;
void test1(){}
void test2(){}
//异步client
class client
{
private:
io_service& ios;
ip::tcp::endpoint ep;
typedef shared_ptr<ip::tcp::socket> sock_pt;
public:
client(io_service& io):ios(io),ep(ip::address::from_string("127.0.0.1"),6688)
{
start();
}
void start()
{
sock_pt sock(new ip::tcp::socket(ios));//智能指针
sock->async_connect(ep,bind(&client::conn_handler,this,placeholders::error,sock));
}
void conn_handler(const system::error_code& ec,sock_pt sock)
{
if (ec)//检测错误码
{
return;
}
cout<<"recive from:";//输出连接的服务器端信息
cout<<sock->remote_endpoint().address()<<" port:"<<sock->remote_endpoint().port()<<endl;
shared_ptr<vector<char>>str(new vector<char>(100,0));//建立接收数据的缓冲区
sock->async_read_some(buffer(*str),bind(&client::read_handler,this,placeholders::error,str));//异步读取数据
start();// 再次启动异步连接
}
void read_handler(const system::error_code& ec,shared_ptr<vector<char>>str)
{
if (ec)
{
return;
}
cout<<&(*str)[0]<<endl;//输出接收的数据
}
};
void test3()
{
try
{
cout<<"client start."<<endl;
io_service ios;
client cl(ios);
ios.run();
}
catch (std::exception& e)
{
cout<<e.what()<<endl;
}
}
void test(char t)
{
std::cout<<"press key====="<<t<<std::endl;
switch (t)
{
case '1':test1();break;
case '2':test2();break;
case '3':test3();break;
case 27:
case 'q':exit(0);break;
default: std::cout<<"default "<<t<<std::endl;break;
}
}
void main()
{
while(1)
test(getch());
}
结果: 不停的执行

[Boost基础]并发编程——asio网络库——异步socket处理的更多相关文章

  1. [Boost基础]并发编程——asio网络库——同步socket处理

    网络通信简述 asio库支持TCP,UDP和ICMP通信协议,它在名字空间boost::asio::ip里提供了大量的网络通信方面的函数和类,很好的封装了原始的Berkeley Socket API, ...

  2. [Boost基础]并发编程——asio网络库——定时器deadline_timer

    asio库基于操作系统提供的异步机制,采用前摄器设计模式(Proactor)实现了可移植的异步(或者同步)IO操作,而且并不要求使用多线程和锁定,有些的避免了多线程编程带来的诸多有害副作用(如条件竞争 ...

  3. Python并发编程06 /阻塞、异步调用/同步调用、异步回调函数、线程queue、事件event、协程

    Python并发编程06 /阻塞.异步调用/同步调用.异步回调函数.线程queue.事件event.协程 目录 Python并发编程06 /阻塞.异步调用/同步调用.异步回调函数.线程queue.事件 ...

  4. python语法基础-并发编程-进程-进程理论和进程的开启

    ############################################## """ 并发编程的相关概念: 进程 1,运行中的程序,就是进程,程序是没有生 ...

  5. python语法基础-并发编程-进程-进程锁和进程间通信

    ###############   守护进程  ############## """ 守护进程 父进程中将一个子进程设置为守护进程,那么这个子进程会随着主进程的结束而结束 ...

  6. 使用 boost.asio 简单实现 异步Socket 通信

     客户端: class IPCClient { public: IPCClient(); ~IPCClient(); bool run(); private: bool connect(); bool ...

  7. 并发编程 —— 自己写一个异步回调 API

    1. 前言 在并发编程中,异步回调的效率不言而喻,在业务开发中,如果由阻塞的任务需要执行,必然要使用异步线程.并且,如果我们想在异步执行之后,根据他的结果执行一些动作. JDK 8 之前的 Futur ...

  8. python基础-并发编程part01

    并发编程 操作系统发展史 穿孔卡片 读取数据速度特别慢,CPU利用率极低 单用户使用 批处理 读取数据速度特别慢,CPU利用率极低 联机使用 脱机批处理(现代操作系统的设计原理) 读取数据速度提高 C ...

  9. python基础-并发编程02

    并发编程 子进程回收的两种方式 join()让主进程等待子进程结束,并回收子进程资源,主进程再结束并回收资源 from multiprocessing import Process import ti ...

随机推荐

  1. 强大的Mockito测试框架(转)

    1.自动生成Mock类在需要Mock的属性上标记@Mock注解,然后@RunWith中配置Mockito的TestRunner或者在setUp()方法中显示调用MockitoAnnotations.i ...

  2. ThinkPHP 3.1.2 模板的使用技巧

    本节课大纲: 一.模板包含 <include file="完整模板文件名" /> <include file="./Tpl/default/Public ...

  3. java学习之动态代理模式

    package com.gh.dynaproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Metho ...

  4. OpenStack导入镜像后Launch不起来的几个问题

    Dashboard上显示state为error 没有其他报错 用nova list找到虚拟机的id 然后nova show,可以得到fault详细信息 也可以查看下面两个log /var/log/no ...

  5. 第一篇:NSOperation的概念

    一.说明 NSOperation的作口:配合使用NSOperation和NSOperationQueue也能实现多线程 NSOperation和NSOperationQueue实现多线程的具体步骤: ...

  6. java 如何自定义异常 用代码展示 真心靠谱

    先建两个自定义的异常类 ChushufuException类 class ChushufuException extends Exception { public ChushufuException( ...

  7. 【转】centos安装memcached+php多服务器共享+session多机共享问题

    参考博文: centos安装memcached 源码安装 Yum安装Memcache Memcached内存分配优化及使用问题 <转>php+memcached 实现session共享 P ...

  8. Reapter 添加删除按钮

    repeater中的删除按钮和datagrid下的删除在实现上,还是有一定的区别的,由于repeater在客户端生成的html代码是非常干净的,所以特别受到众多web2.0网站的欢迎(不像datagr ...

  9. python读写zip文件

    zipfile.ZipFile(fileName[, mode[, compression[, allowZip64]]]) fileName是没有什么疑问的了. mode和一般的文件操作一样,'r' ...

  10. Week7(10月24日)

    Part I:提问  =========================== 1.数据验证属性的练习. 按要求写出教室和课程的模型类. (1)教室类主键不自动增值,手工输入. (2)教室名字不超过10 ...