C++面向对象网络编程之SockServer

/************************************************************************/
// Copyright 2015, han_gangbiao. All rights reserved.
// 
// [Time]:      2015-6-27 22:19:12
// [Author]:    han_gangbiao
// [Info]:      TCP-Server Demo
/************************************************************************/

#include "stdafx.h"
#include "xsmart.h"
#include "xnet/SockAcceptor.h"
#include "xbase/xlogger.h"
#include "xbase/xthread.h"
#include <iostream>

int main(int argc, char* argv[])
{
    smart::XSmartLib::init();
    XLOG_SET_STDERR(true);
    std::cout<<smart::XSmartLib::getLibInfo()<<std::endl;

    XNetAddr net_addr_listen("0.0.0.0", 8800);
    XSockAcceptor acceptor;
    if( acceptor.open(net_addr_listen, false, 1) < 0 )
    {
        XLOG_INFO("XSockAcceptor open failed.");
    }

    while(1) {
        XSockStream peer;
        XNetAddr peer_addr;
        if( acceptor.accept(peer, &peer_addr) < 0 )
        {
            printf("accept error!\n");
            SLEEP_MS(3000);
            continue;
        }
        XLOG_INFO( "connection from peer[%s]", peer_addr.get_ipstr() );

        char buffer[4096] = {0};
        int bytes_received;
        while((bytes_received = peer.recv(buffer, sizeof(buffer))) > 0)
        {
            buffer[bytes_received] = '\0';
            XLOG_INFO("recv data: %s", buffer);

            peer.send(buffer, bytes_received);
        }

        peer.close();
        XLOG_INFO("close the socket!");
    }
    smart::XSmartLib::unInit();
    return 0;
}

你可能感兴趣的:(C/C++网络编程)