本篇内容介绍了“socket通信怎么使用”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
#include <boost/bind.hpp> #include <boost/asio.hpp> #include <boost/thread.hpp> using boost::asio::io_service; using boost::asio::ip::tcp; using boost::system::error_code; using boost::asio::deadline_timer; using boost::asio::buffer; class MyNet { public: void Accept(unsigned short port, boost::function<void ()> fun) { _pAcceptor = new tcp::acceptor(_ios, tcp::endpoint(tcp::v4(), port)); _pTimer = new deadline_timer(_ios); _pClentSkt = new tcp::socket(_ios); _pAcceptor->async_accept(*_pClentSkt, boost::bind(&MyNet::AcceptHandle, this, boost::asio::placeholders::error, //传递错误码 fun//传递一个函数指针 )); _ios.reset(); //充值事件循环状态 if (_ios.run() == 0) //启动事件循环 { throw std::runtime_error("io_service run return 0."); } } void Send(const string& data) { _pClentSkt->write_some(buffer(data, data.size())); } string Recv() { _ret = _pClentSkt->read_some(buffer(_buf, 1024)); return string(_buf, _ret); } void Close() { _mutex.lock(); _pAcceptor->close(); _pClentSkt->shutdown(tcp::socket::shutdown_both); _pClentSkt->close(); _ios.stop(); _mutex.unlock(); } string GetClientIp() {//获得客户端的ip boost::asio::ip::tcp::endpoint ep = _pClentSkt->remote_endpoint(); return ep.address().to_string(); } unsigned short GetPort() {//获得监控的端口 return _pAcceptor->local_endpoint().port(); } static unsigned short GetLocalValidPort() {//随机过去一个本机的可用端口 io_service ios; tcp::acceptor acceptor(ios, tcp::endpoint(tcp::v4(), 0)); tcp::acceptor::endpoint_type et = acceptor.local_endpoint(); return et.port(); } static string GetLocalIp() {//获取本机ip boost::asio::io_service io_service; tcp::resolver resolver(io_service); tcp::resolver::query query(boost::asio::ip::host_name(), ""); tcp::resolver::iterator iter = resolver.resolve(query); tcp::resolver::iterator end; // End marker. if (iter != end) { tcp::endpoint ep = *iter; return ep.address().to_string(); } } ~MyNet(void) { delete _pTimer; delete _pAcceptor; delete _pClentSkt; } protected: void AcceptHandle(const error_code& error, boost::function<void ()> fun) {//异步接收连接的回调函数 if (error) return; //传递进来的函数指针fun未用到,本来是为了启动此函数的线程,boost::thread trd(fun); } private: io_service _ios; tcp::acceptor* _pAcceptor; tcp::socket* _pClentSkt; tcp::socket* _pClentTmp; deadline_timer* _pTimer; char _buf[1024]; size_t _ret; static string _ip; boost::mutex _mutex; };
“socket通信怎么使用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。