Sloppy's Blog

Asio使用小实例

写了个小型的ASIO TcpSocket测试小实例,分两部分,客户端C++,服务端模拟是Python

C++ 代码如下:

std::thread t([=]() {
    asio::io_service io_service;
    asio::ip::tcp::endpoint end_point(asio::ip::address::from_string("10.10.10.111"), 8088);
    asio::ip::tcp::socket socket(io_service);
    asio::error_code ec;
    socket.connect(end_point, ec);
    if (ec) {
        CCLOG("error");
        socket.close();
    }
    else {
        CCLOG("Success");
        char buf[100];
        size_t len = socket.read_some(asio::buffer(buf), ec);// 读取数据
        if (len > 0) {
            std::string value(buf, len);
            CCLOG("value:%s", value.c_str());
            std::cout.write(buf, len);
            socket.write_some(asio::buffer("123456"), ec);// 发送数据
        }

    }
});
t.detach();

服务端Python代码:

def initSock():
    sock = socket(AF_INET,SOCK_STREAM)
    ADDR=("10.10.10.111", 8088)
    sock.bind(ADDR)
    sock.listen(5)
    while True:
        print "waiting for connectiong"
        tcpClient,addr = sock.accept()
        print ('connect from',addr)
        s  = 'Hello world %s' %(ctime())
        tcpClient.send(s.encode("utf-8"))
        while True:
            try:
                data = tcpClient.recv(1024)
            except:
                print("exception")
                tcpClient.close()
                break
            if not data:
                print("invalid data")
                break;
            else:
                print data

    tcpClient.close()
    sock.close()