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:/ ...
随机推荐
- linux 基础命令与文件管理
Linux终端介绍 Shell提示符 Bash Shell基本语法 基本命令的使用:ls.pwd.cd 查看系统和BIOS硬件时间 Linux如何获得帮助 Linux关机命令:shutdow.in ...
- 高性能异步图片加载器的JS库:lazysizes
<script src="lazysizes.min.js" async=""></script> 使用示例 <!-- non-r ...
- 机器学习——支持向量机(SVM)之拉格朗日乘子法,KKT条件以及简化版SMO算法分析
SVM有很多实现,现在只关注其中最流行的一种实现,即序列最小优化(Sequential Minimal Optimization,SMO)算法,然后介绍如何使用一种核函数(kernel)的方式将SVM ...
- .net core教程
https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/start-mvc
- jQuery 人脸识别插件,支持图片和视频
jQuery Face Detection 是一款人脸检测插件,能够检测到图片,视频和画布中的人脸坐标.它跟踪人脸并输出人脸模型的坐标位置为一个数组.我们相信,面部识别技术能够给我们的 Web 应用带 ...
- HTML 5 胜出:XHTML2 宣告夭折
自HTML 5 和XHTML 2规范草稿公布以来,一直存在很大的争议.HTML 5是由包括Google.Mirosoft.Mozilla.Opera.Apple在内多家浏览器厂商共同起草的下一代web ...
- Yii2 ActiveRecord save失败
当给AR写beforeSave方法时,注意返回true还是false.如果没有返回值,或者返回false,那么就不会存入数据库.如下 晚上写代码的时候beforeSave忘了返回true,导致无法存入 ...
- JavaScript对象创建,继承
创建对象 在JS中创建对象有很多方式,第一种: var obj = new Object(); 第二种方式: var obj1 = {};//对象直面量 第三种方式:工厂模式 function Per ...
- C#数字日期装换为中文日期
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...
- 手写一个allocator
似乎就像是一个计算机原理的实践.. 首先介绍一下大多数操作系统的内存架构..对于某个程序它会认为自己是独占了整个系统的所有内存在运行的这样才能方便移植,因此人们搞出了虚拟内存和物理内存的区别,于是人们 ...