前些日子研究了一个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. jquery缓存使用jquery.cookies.2.2.0.min.js

    $.cookies.set(key, obj, { hoursToLive: 2}); key标识的键 , obj存入的值可以缓存json对象, hoursToLive 缓存小时数 $.cookies ...

  2. DEDEcms 在php5.4以上 后台登录空白解决办法

    本次环境php5.5 首先确定 dede data文件夹已经有写入权限 775 777都可以 然后再远程桌面或者FTP修改 include/userlogin.class.php 文件 注释掉下面六句 ...

  3. 深入理解javascript原型和闭包 (转)

    该教程绕开了javascript的一些基本的语法知识,直接讲解javascript中最难理解的两个部分,也是和其他主流面向对象语言区别最大的两个部分--原型和闭包,当然,肯定少不了原型链和作用域链.帮 ...

  4. RESTful API URI 设计的一些总结

    非常赞的四篇文章: Resource Naming Best Practices for Designing a Pragmatic RESTful API 撰写合格的 REST API JSON 风 ...

  5. shell 计算2

    转载 http://www.th7.cn/system/lin/201309/44683.shtml expr bc 在Linux下做算术运算时你是如何进行的呢?是不是还在用expr呢?你会说我还会b ...

  6. java多线程操作

    进程是程序的一次动态的执行过程,它经历了从代码加载.执行完毕的一个完整过程,这个过程也是进程本身从产生.发展到最终消亡的过程. 多线程是实现并发机制的一种有效的手段.进程和线程一样,都是实现并发的一个 ...

  7. Git学习笔记与IntelliJ IDEA整合

    Git学习笔记与IntelliJ IDEA整合 一.Git学习笔记(基于Github) 1.安装和配置Git 下载地址:http://git-scm.com/downloads Git简要使用说明:h ...

  8. EBS 中经常用到的一些值集

    名称                                 值集                                                                ...

  9. 一个java源文件中为什么只能有一个public类。

    我们都遇到过一个源文件中有多个java类,但当第一个类使用public修饰时,如果下面还有类使用public修饰,会报错.也就是是说一个java源文件最多只能有一个public类. 当有一个publi ...

  10. Format 函数示例

    Format 函数示例本示例显示用 Format 函数做格式化输出的不同用法.对于日期分隔号(/),时间分隔号(:),以及 AM/ PM 等文本而言,其真正的显示格式会因计算机上的国际标准不同而有所差 ...