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

#include "stdafx.h"
#include "acl_cpp/lib_acl.hpp"
#include <thread>

using namespace acl;

int _tmain(int argc, _TCHAR* argv[])
{
    acl_cpp_init();
    
    // 2. 创建服务端 socket
    acl::server_socket server;
    // 3. 绑定并监听
    if (!server.open("127.0.0.1:12345"))
    {
        std::cerr << "监听端口失败!" << std::endl;
        return 1;
    }
    std::cout << "服务端启动成功,监听 127.0.0.1:8888 ..." << std::endl;

    while (true) 
    {
        acl::socket_stream* client = server.accept();
        if (client == nullptr) 
        {
            std::cerr << "接受连接失败!" << std::endl;
            break;
        }
        string strPeerIp = client->get_peer_ip();
        string strLocalIp = client->get_local_ip();

        std::cout << "客户端已连接!" << std::endl;

        std::thread thread([=] 
        {
            char buf[256];
            int ret = client->read(buf, sizeof(buf), false); 
            if (ret > 0) 
            {
                client->write(buf, ret); 
            }
            delete client;
        });
        thread.detach();
    }

    return 0;
}

更多推荐