c++ boost asio库初学习
前些日子研究了一个c++的一个socket库,留下范例代码给以后自己参考。
同步server:
// asio_server.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
// #include "stdafx.h"
#include "boost/asio.hpp"
#include "boost/bind.hpp" using namespace boost::asio; io_service service;
size_t read_complete(char * buff, const boost::system::error_code & err, size_t bytes) {
if (err) return ;
bool found = std::find(buff, buff + bytes, '\n') < buff + bytes;
// 我们一个一个读取直到读到回车,不缓存
return found ? : ;
}
void handle_connections() {
ip::tcp::acceptor acceptor(service, ip::tcp::endpoint(ip::tcp::v4(), ));
char buff[];
while (true) {
ip::tcp::socket sock(service);
acceptor.accept(sock);
int bytes = read(sock, buffer(buff), boost::bind(read_complete, buff, _1, _2));
std::string msg(buff, bytes);
sock.write_some(buffer(msg));
sock.close();
}
}
int _tmain(int argc, char* argv[]) {
handle_connections();
}
同步client:
// boost_aiso_test.cpp : コンソール アプリケーションのエントリ ポイントを定義します。
// #include "stdafx.h" #include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/thread.hpp> using namespace boost::asio; io_service service;
ip::address_v4 add;
ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"), ); size_t read_complete(char * buf, const boost::system::error_code & err, size_t bytes)
{
if (err) return ;
bool found = std::find(buf, buf + bytes, '\n') < buf + bytes;
// 我们一个一个读取直到读到回车,不缓存
return found ? : ;
}
void sync_echo(std::string msg) {
msg += "\n";
ip::tcp::socket sock(service);
sock.connect(ep);
sock.write_some(buffer(msg));
char buf[];
int bytes = read(sock, buffer(buf), boost::bind(read_complete, buf, _1, _2));
std::string copy(buf, bytes - );
msg = msg.substr(, msg.size() - );
std::cout << "server echoed our " << msg << ": " << (copy == msg ? "OK" : "FAIL") << std::endl;
sock.close();
}
int _tmain(int argc, char* argv[]) {
char* messages[] = { "John says hi", "so does James", "Lucy just got home", "Boost.Asio is Fun!", };
boost::thread_group threads;
for (char ** message = messages; *message; ++message) {
threads.create_thread(boost::bind(sync_echo, *message));
boost::this_thread::sleep(boost::posix_time::millisec());
}
threads.join_all();
}
-------------------------------------------------------- 异步是参考其他博客 --------------------------------------------------------
异步server:
#include "stdafx.h" #include <boost/asio.hpp>
#include <iostream>
using namespace boost::asio;
class Server
{
typedef ip::tcp::socket socket_type;
typedef std::shared_ptr<socket_type> sock_ptr;
public:
Server() :m_acceptor(m_io, ip::tcp::endpoint(ip::tcp::v4(), ))
{
accept();
}
void run()
{
m_io.run();
}
private:
void accept()
{
sock_ptr sock(new socket_type(m_io));
m_acceptor.async_accept(*sock,
std::bind(&Server::accept_handler, this, std::placeholders::_1, sock));
}
void accept_handler(const boost::system::error_code& ec, sock_ptr sock)
{
if (ec)
{
return;
}
std::cout << "client:";
std::cout << sock->remote_endpoint().address() << std::endl;
sock->async_write_some(buffer("hello asio"),
std::bind(&Server::write_handler, this, std::placeholders::_1));
accept();
}
void write_handler(const boost::system::error_code&)
{
std::cout << "send msg complete." << std::endl;
}
private:
io_service m_io;
ip::tcp::acceptor m_acceptor;
};
int main()
{
try
{
std::cout << "server" << std::endl;
Server svr;
svr.run();
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
return ;
}
异步client:
#include "stdafx.h" #include <boost/asio.hpp>
#include <iostream>
using namespace boost::asio;
class Client
{
typedef ip::tcp::socket socket_type;
typedef std::shared_ptr<socket_type> sock_ptr;
public:
Client() :m_ep(ip::address::from_string("127.0.0.1"), )
{
start();
}
void run()
{
m_io.run();
}
private:
void start()
{
sock_ptr sock(new socket_type(m_io));
sock->async_connect(m_ep, std::bind(&Client::connect_handler, this, std::placeholders::_1, sock));
}
void connect_handler(const boost::system::error_code& ec, sock_ptr sock)
{
if (ec)
{
return;
}
std::cout << "receive from:" << sock->remote_endpoint().address() << std::endl;
sock->async_read_some(buffer(m_buf),
std::bind(&Client::read_handler, this, std::placeholders::_1));
}
void read_handler(const boost::system::error_code& ec)
{
if (ec)
{
return;
}
std::cout << m_buf << std::endl;
}
private:
io_service m_io;
ip::tcp::endpoint m_ep;
enum { max_length = };
char m_buf[max_length];
};
int main()
{
try
{
std::cout << "client start." << std::endl;
Client cl;
cl.run();
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
getchar();
return ;
}
c++ boost asio库初学习的更多相关文章
- boost asio 学习(九) boost::asio 网络封装
http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting- started-with-boostasio?pg=10 9. A ...
- boost asio 学习(八) 网络基础 二进制写发送和接收
http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting- started-with-boostasio?pg=9 8. Net ...
- BOOST ASIO 学习专贴
本文已于20170903更新完毕,所有boost asio 代码均为本人手抄.编译器为vs2013,并且所有代码已经上传,本文下方可下载源码 为了学习boost asio库,我是从boost的官方bo ...
- boost::asio译文
Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENS ...
- Boost.Asio技术文档
Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENSE_1_ ...
- Boost.Asio c++ 网络编程翻译(21)
同步VS异步 Boost.Asio的作者做了一个非常惊艳的工作:它能够让你在同步和异步中自由选择,从而更好的适应你的应用. 在之前的章节中,我们学习了每种类型应用的框架,比方同步client,同步服务 ...
- 使用Boost.Asio编写通信程序
摘要:本文通过形像而活泼的语言简单地介绍了Boost::asio库的使用,作为asio的一个入门介绍是非常合适的,可以给人一种新鲜的感觉,同时也能让体验到asio的主要内容. Boost.Asio是一 ...
- 使用boost.asio实现网络通讯
#include <boost/asio.hpp> #define USING_SSL //是否加密 #ifdef USING_SSL #include <boost/asio/ss ...
- Boost Asio介绍--之一
原文:http://www.tuicool.com/articles/YbeYR3 Boost Asio介绍--之一 时间 2014-03-26 17:57:39 CSDN博客 原文 http:/ ...
随机推荐
- jquery缓存使用jquery.cookies.2.2.0.min.js
$.cookies.set(key, obj, { hoursToLive: 2}); key标识的键 , obj存入的值可以缓存json对象, hoursToLive 缓存小时数 $.cookies ...
- latex均方极限符号l.i.m在lyx下的输入方法
$\mathop{l.i.m}\limits_{x\to +\infty}$ 命令说明: 1.指定数学环境$$ 2.\mathop{l.i.m}指数学符号自定义为l.i.m 3.\limits_{x\ ...
- 总是多次出现 那个同样的 权限错误 _storage_write_error_, 所以一开始就把机器设好setenforce 0
把根目录下的所有文件/目录, 都设为权限777. 好像没有必要把所有的东西, 都设为777, 实际上问题是由selinux引起的, 所以, 只要把相应的目录, 不一定是所有的目录, 只是要写入内容的目 ...
- SQL Server启动的几种方法
SQL Server 启动有以下几种方法: (1)在Control Panel——Administrative Tools——Services,找到SQL Server (XXX)进行启动. 其中XX ...
- GNU Radio Radar Toolbox
GNU Radio Radar Toolbox Install guide Change to any folder in your home directory and enter followin ...
- EBS提交请求出现REP-3000错误
在AIX上利用并发请求提交报表的時候,出现如下错误:REP-3000: Internal error starting Oracle Toolkit.这是因为Report Server需要X-Wind ...
- 转载:Centos7 从零编译配置Memcached
序言 Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度. Memca ...
- java日期工具类
public class UtilDate { /** 年月日时分秒(无下划线) yyyyMMddHHmmss */ public static final String dtLong = " ...
- phalcon3.0.1默认多模块生成的几个bug
发现用Phalcon DevTools (3.0.0)生成的多模块有一些bug: 默认的路由定义,字符串替换有误 原代码// $namespace = str_replace('Module','Co ...
- angularJS实践过程中出现的问题总结
同名服务 在一次项目里,之前是同事写的.我有一次在异步获取服务器上的数据时,习惯把api地址写在一个服务Store里,但是程序总是返回Store.api.get()里的get is undefined ...