boost::asio之(一)简单客户端服务器回显功能

客户端:

// BoostDev.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/cerrno.hpp>



size_t read_complete(char * buf, const boost::system::error_code & err, size_t bytes)
{
    if (err) return 0;
    bool found = std::find(buf, buf + bytes, '\n') < buf + bytes
        ;
    // 我们一个一个读取直到读到回车, 不缓存
    return found ? 0 : 1;
}
void sync_echo(std::string msg) {
    msg += "\n";
    std::cout << msg << std::endl;
    boost::asio::io_service service;
    //boost::asio::ip::tcp::endpoint ep(boost::asio::ip::tcp::v4(), 2001); // listen on 2001
    boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string("127.0.0.1"),2002);
    boost::asio::ip::tcp::socket sock(service);
    sock.connect(ep);
    sock.write_some(boost::asio::buffer(msg));
    char buf[1024];
    int bytes = read(sock, boost::asio::buffer(buf), boost::bind(read_complete, buf, _1, _2));
    std::cout << bytes << std::endl;
    std::string copy(buf, bytes - 1);
    msg = msg.substr(0, msg.size() - 1);
    std::cout << "server echoed our " << msg << ": " << (copy == msg ? "OK" : "FAIL") << std::endl;
    sock.close();
}
int main(int argc, char* argv[]) {
    const char* messages[] = {"John says hi", "so does James", "Lucyjust got home", "Boost.Asio is Fun!", 0 };
    boost::thread_group threads;
    for (const char ** message = messages; *message; ++message) {
        threads.create_thread(boost::bind(sync_echo, *message));
        boost::this_thread::sleep(boost::posix_time::millisec(100));
    } 
    threads.join_all();
}

 

服务端:

// BoostSever.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/thread.hpp>


size_t read_complete(char * buff, const boost::system::error_code & err, size_t
    bytes) {
    if (err) return 0;
    bool found = std::find(buff, buff + bytes, '\n') < buff + bytes;
    // 我们一个一个读取直到读到回车, 不缓存
    return found ? 0 : 1;
} 
void handle_connections() {
    boost::asio::io_service service;
    boost::asio::ip::tcp::acceptor acceptor(service, boost::asio::ip::tcp::endpoint(boost::asio::ip::address::from_string("127.0.0.1"), 2002));
    char buff[1024];
    while (true) {
        boost::asio::ip::tcp::socket sock(service);
        acceptor.accept(sock);
        int bytes = read(sock, boost::asio::buffer(buff), boost::bind(read_complete, buff, _1, _2));
        std::cout << bytes << std::endl;
        std::string msg(buff, bytes);
        sock.write_some(boost::asio::buffer(msg));
        sock.close();
    }
} 
int main(int argc, char* argv[]) {
    handle_connections();
}

 

posted @ 2019-01-10 15:52  且听风吟-wuchao  阅读(878)  评论(1编辑  收藏  举报