免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 5468 | 回复: 4
打印 上一主题 下一主题

[C++] boost asio的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-12-12 16:28 |只看该作者 |倒序浏览
请问,我现在已经和客户机连上了,怎样获取它的端口?怎样主动对它发数据。

我已经有的对象

tcp::socket socket_;
handler_allocator allocator_;

论坛徽章:
0
2 [报告]
发表于 2007-12-12 16:29 |只看该作者
我的代码

#include <cstdlib>
#include <iostream>
#include <boost/aligned_storage.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>

using namespace std;
using boost::asio::ip::tcp;

// Class to manage the memory to be used for handler-based custom allocation.
// It contains a single block of memory which may be returned for allocation
// requests. If the memory is in use when an allocation request is made, the
// allocator delegates allocation to the global heap.
class handler_allocator
        : private boost::noncopyable
{
public:
        handler_allocator()
                : in_use_(false)
        {
        }

        void* allocate(std::size_t size)
        {
                if (!in_use_ && size < storage_.size)
                {
                        in_use_ = true;
                        return storage_.address();
                }
                else
                {
                        return :perator new(size);
                }
        }

        void deallocate(void* pointer)
        {
                if (pointer == storage_.address())
                {
                        in_use_ = false;
                }
                else
                {
                        :perator delete(pointer);
                }
        }

private:
        // Storage space used for handler-based custom memory allocation.
        boost::aligned_storage<1024> storage_;

        // Whether the handler-based custom allocation storage has been used.
        bool in_use_;
};

// Wrapper class template for handler objects to allow handler memory
// allocation to be customised. Calls to operator() are forwarded to the
// encapsulated handler.
template <typename Handler>
class custom_alloc_handler
{
public:
        custom_alloc_handler(handler_allocator& a, Handler h)
                : allocator_(a),
                handler_(h)
        {
        }

        template <typename Arg1>
        void operator()(Arg1 arg1)
        {
                handler_(arg1);
        }

        template <typename Arg1, typename Arg2>
        void operator()(Arg1 arg1, Arg2 arg2)
        {
                handler_(arg1, arg2);
        }

        friend void* asio_handler_allocate(std::size_t size,
                custom_alloc_handler<Handler>* this_handler)
        {
                return this_handler->allocator_.allocate(size);
        }

        friend void asio_handler_deallocate(void* pointer, std::size_t size,
                custom_alloc_handler<Handler>* this_handler)
        {
                this_handler->allocator_.deallocate(pointer);
        }

private:
        handler_allocator& allocator_;
        Handler handler_;
};

// Helper function to wrap a handler object to add custom allocation.
template <typename Handler>
inline custom_alloc_handler<Handler> make_custom_alloc_handler(
        handler_allocator& a, Handler h)
{
        return custom_alloc_handler<Handler>(a, h);
}

class session
        : public boost::enable_shared_from_this<session>
{
public:
        session(boost::asio::io_service& io_service)
                : socket_(io_service)
        {
        }

        tcp::socket& socket()
        {
                return socket_;
        }

        void start()
        {
                socket_.async_read_some(boost::asio::buffer(data_),
                        make_custom_alloc_handler(allocator_,
                        boost::bind(&session::handle_read,
                        shared_from_this(),
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred)));
        }

        void handle_read(const boost::system::error_code& error, size_t bytes_transferred)
        {
                if (!error)
                {
                        cout << "client send message:";
                        for(size_t i = 0; i < bytes_transferred; i ++ )
                        {
                                cout << data_[ i ];
                        }
                        cout << endl;

                        boost::asio::async_write(socket_,
                                boost::asio::buffer(data_, bytes_transferred),
                                make_custom_alloc_handler(allocator_,
                                boost::bind(&session::handle_write,
                                shared_from_this(),
                                boost::asio::placeholders::error)));
                }
        }

        void handle_write(const boost::system::error_code& error)
        {
                if (!error)
                {
                        socket_.async_read_some(boost::asio::buffer(data_),
                                make_custom_alloc_handler(allocator_,
                                boost::bind(&session::handle_read,
                                shared_from_this(),
                                boost::asio::placeholders::error,
                                boost::asio::placeholders::bytes_transferred)));
                }
        }

private:
        // The socket used to communicate with the client.
        tcp::socket socket_;

        // Buffer used to store data received from the client.
        boost::array<char, 1024> data_;

        // The allocator to use for handler-based custom memory allocation.
        handler_allocator allocator_;
};

typedef boost::shared_ptr<session> session_ptr;

class server
{
public:
        server(boost::asio::io_service& io_service, short port)
                : io_service_(io_service),
                acceptor_(io_service, tcp::endpoint(tcp::v4(), port))
        {
                session_ptr new_session(new session(io_service_));
                acceptor_.async_accept(new_session->socket(),
                        boost::bind(&server::handle_accept, this, new_session,
                        boost::asio::placeholders::error));
        }

        void handle_accept(session_ptr new_session, const boost::system::error_code& error)
        {
                if (!error)
                {
                        new_session->start();
                        new_session.reset(new session(io_service_));
                        acceptor_.async_accept(new_session->socket(),
                                boost::bind(&server::handle_accept, this, new_session,
                                boost::asio::placeholders::error));
                }
        }

private:
        boost::asio::io_service& io_service_;
        tcp::acceptor acceptor_;
};

int main(int argc, char* argv[])
{
        int port;

        //try
        //{
        //        if (argc != 2)
        //        {
        //                std::cerr << "Usage: server <port>\n";
        //                return 1;
        //        }
        //        port = atoi(argv[1]);
        //}

        try
        {

                port = 8888;

                boost::asio::io_service io_service;

                using namespace std; // For atoi.
                server s(io_service, port);

                io_service.run();
        }
        catch (boost::system::error_code& e)
        {
                std::cerr << e << "\n";
        }
        catch (std::exception& e)
        {
                std::cerr << "Exception: " << e.what() << "\n";
        }

        return 0;
}

论坛徽章:
0
3 [报告]
发表于 2007-12-12 20:48 |只看该作者
楼主的例子是
boost_asio_0_3_8/libs/asio/example/allocation

你可以参考
boost_asio_0_3_8/libs/asio/example/chat
这个例子比较全面

论坛徽章:
0
4 [报告]
发表于 2007-12-12 22:06 |只看该作者
谢谢,我现在已经在看chat了。但我还是找不到客户机的端口

论坛徽章:
0
5 [报告]
发表于 2007-12-12 23:29 |只看该作者
原帖由 lokeio 于 2007-12-12 22:06 发表
谢谢,我现在已经在看chat了。但我还是找不到客户机的端口


你可以试一下:
tcp::endpoint endpoint = socket_.remote_endpoint();
unsigned short port = endpoint.port();





chat中的部分代码
using boost::asio::ip::tcp;

class chat_session
  : public chat_participant,
    public boost::enable_shared_from_this<chat_session>
{
  // ...
private:
  tcp::socket socket_;
  // ...
};



boost::asio中的类
typedef basic_stream_socket<tcp> socket;

template <typename Protocol,
    typename StreamSocketService = stream_socket_service<Protocol> >
class basic_stream_socket
  : public basic_socket<Protocol, StreamSocketService>
{
  // ...
};


template <typename Protocol, typename SocketService>
class basic_socket
  : public basic_io_object<SocketService>,
    public socket_base
{
  // ...

  endpoint_type remote_endpoint() const;
  endpoint_type remote_endpoint(boost::system::error_code& ec) const;

  // ..

};

[ 本帖最后由 westgarden 于 2007-12-13 11:45 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP