1. 程式人生 > >boost::asio之(一)簡單客戶端服務器回顯功能

boost::asio之(一)簡單客戶端服務器回顯功能

讀取 緩存 argc john sock n! return byte 服務

客戶端:

// 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();
}

boost::asio之(一)簡單客戶端服務器回顯功能