您好,登錄后才能下訂單哦!
本篇內容介紹了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。