#include <sstream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>

using namespace boost::asio;
typedef boost::shared_ptr<ip::tcp::socket> socket_Ptr;


void cilent_session(socket_Ptr socket);

int main()
{
    //必须定义一个io_service实例,使用io_service与系统的输入输出进行交互
    io_service service;

    //TCP端点的类型, 监听端口
    ip::tcp::endpoint ep(ip::tcp::v4(), 7200);

    //TCP接受器类型
    ip::tcp::acceptor accept(service, ep);

    while (true)
    {
        //定义客户端的套接字
        socket_Ptr cli_socket(new ip::tcp::socket(service));

        //阻塞,等待客户端连接
        accept.accept(*cli_socket);

        // 打印与本机服务器取得连接的客户端IP地址
        std::cout << "client IP: " << cli_socket->remote_endpoint().address() << std::endl;

        //一个连接,一个线程,在线程中操作读写socket。
        boost::thread(boost::bind(cilent_session, cli_socket));
    }
    return 0;
}


void cilent_session(socket_Ptr socket)
{
    while (true)
    {
        char data[1024];

        //客户端主动断开,程序会抛异常,必须要抓取异常,不然程序挂掉。
        try
        {
            //阻塞读取
            size_t len = socket->read_some(buffer(data));
       if (0 == len) { std::cout << "客户端断开" << std::endl; return; } if (len > 0) { len = write(*socket, buffer("ok", 2)); if (len <= 0) { std::cout << "发送异常 断开连接" << std::endl; return; } } } catch (boost::system::system_error e) { std::cout << "抛出异常 :" << e.code() << std::endl; return; } } }

 

 

//客户端
#include <cstdio> #include <iostream> #include <sstream> #include <boost/asio.hpp> #include <boost/bind.hpp> #include <boost/thread/thread.hpp> using namespace boost::asio; typedef boost::shared_ptr<ip::tcp::socket> socket_Ptr; void cilent_session(socket_Ptr socket); int main() { //必须定义一个io_service实例,使用io_service与系统的输入输出进行交互 io_service service; ip::tcp::endpoint ep(ip::address::from_string("192.168.56.1"), 7200); //定义套接字 socket_Ptr socketPtr(new ip::tcp::socket(service)); //错误码 boost::system::error_code ec; // 连接服务器 socketPtr->connect(ep, ec); if (ec) { std::cout << boost::system::system_error(ec).what() << std::endl; return -1; } std::cout << "connect ..." << std::endl; //连接上服务,在线程中操作读写socket。 boost::thread(boost::bind(cilent_session, socketPtr)); while (true) { sleep(1000); } return 0; } void cilent_session(socket_Ptr socket) { while (true) { char data[1024] = { '\0' }; //客户端主动断开,程序会抛异常,必须要抓取异常,不然程序挂掉。 try { //阻塞读取 size_t len = socket->read_some(buffer(data)); std::cout << "recv len = " << len << std::endl; if (0 == len) { std::cout << "服务端断开" << std::endl; return; } if (len > 0) { len = write(*socket, buffer("ok", 2)); if (len <= 0) { std::cout << "发送异常 断开连接" << std::endl; return; } } } catch (boost::system::system_error e) { std::cout << "抛出异常 :" << e.code() << std::endl; return; } } }

 

相关文章:

  • 2022-12-23
  • 2022-01-09
  • 2021-07-27
  • 2022-01-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-27
猜你喜欢
  • 2022-01-07
  • 2021-06-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案