前些日子研究了一个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库初学习的更多相关文章

  1. boost asio 学习(九) boost::asio 网络封装

    http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting- started-with-boostasio?pg=10 9. A ...

  2. boost asio 学习(八) 网络基础 二进制写发送和接收

    http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting- started-with-boostasio?pg=9 8. Net ...

  3. BOOST ASIO 学习专贴

    本文已于20170903更新完毕,所有boost asio 代码均为本人手抄.编译器为vs2013,并且所有代码已经上传,本文下方可下载源码 为了学习boost asio库,我是从boost的官方bo ...

  4. boost::asio译文

        Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENS ...

  5. Boost.Asio技术文档

    Christopher Kohlhoff Copyright © 2003-2012 Christopher M. Kohlhoff 以Boost1.0的软件授权进行发布(见附带的LICENSE_1_ ...

  6. Boost.Asio c++ 网络编程翻译(21)

    同步VS异步 Boost.Asio的作者做了一个非常惊艳的工作:它能够让你在同步和异步中自由选择,从而更好的适应你的应用. 在之前的章节中,我们学习了每种类型应用的框架,比方同步client,同步服务 ...

  7. 使用Boost.Asio编写通信程序

    摘要:本文通过形像而活泼的语言简单地介绍了Boost::asio库的使用,作为asio的一个入门介绍是非常合适的,可以给人一种新鲜的感觉,同时也能让体验到asio的主要内容. Boost.Asio是一 ...

  8. 使用boost.asio实现网络通讯

    #include <boost/asio.hpp> #define USING_SSL //是否加密 #ifdef USING_SSL #include <boost/asio/ss ...

  9. Boost Asio介绍--之一

    原文:http://www.tuicool.com/articles/YbeYR3 Boost Asio介绍--之一 时间 2014-03-26 17:57:39  CSDN博客 原文  http:/ ...

随机推荐

  1. 关于Nginx的一些优化(突破十万并发)

    nginx指令中的优化(配置文件) worker_processes 8; nginx进程数,建议按照cpu数目来指定,一般为它的倍数. worker_cpu_affinity 00000001 00 ...

  2. 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\ ...

  3. 第一章 Part 1/2 Git 一览

    虽然这个系列的文章主要关注的是Github,然而首先了解下Git的基本概念和名词也是非常有帮助的. 工作目录(Working Directory) 工作目录是你个人计算机上的一个目录.在该目录下,每一 ...

  4. jQuery中Animate进阶用法(一)

    jQuery中animate的用法你了解多少呢?如果仅仅是简单的移动位置,显示隐藏,哦!天哪你在浪费资源!因为animate太强大了,你可以有很多意想不到的用法!让我们一起研究一下吧~~ 首先要了解j ...

  5. Safari new Date()

    最近在敲代码的时候不觉得Safari有什么兼容问题,相比较的更多的时候再考虑ie,结果今天就栽在了Safari日期格式化上面了. 正如前面说的没有特别注意Safari的兼容问题所以特地粘贴这个打开Sa ...

  6. 我的vimrc

    set nocompatible set langmenu=en_USlet $LANG= 'en_US' source $VIMRUNTIME/vimrc_example.vim source $V ...

  7. 前端构建工具之gulp(一)「图片压缩」

    前端构建工具之gulp(一)「图片压缩」 已经很久没有写过博客了,现下终于事情少了,开始写博吧 今天网站要做一些优化:图片压缩,资源合并等 以前一直使用百度的FIS工具,但是FIS还没有提供图片压缩的 ...

  8. nodejs express下使用redis管理session

    Session实现原理 实现请求身份验证的方式很多,其中一种广泛接受的方式是使用服务器端产生的Session ID结合浏览器的Cookie实现对Session的管理,一般来说包括以下4个步骤: 服务器 ...

  9. spring data jpa分页

    controller层 @RequestMapping(value="/search") @ResponseBody public String search(HttpServle ...

  10. html meta标签属性与内容

    meta是html语言head区的一个辅助性标签.也许你认为这些代码可有可无.其实如果你能够用好meta标签,会给你带来意想不到的效果,meta标签的作用有:搜索引擎优化(SEO),定义页面使用语言, ...