pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

如何在斷開連接后干凈地重新連接 boost::socket?

How do I cleanly reconnect a boost::socket following a disconnect?(如何在斷開連接后干凈地重新連接 boost::socket?)
本文介紹了如何在斷開連接后干凈地重新連接 boost::socket?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我的客戶端應用程序使用 boost::asio::ip::tcp::socket 連接到遠程服務器.如果應用失去與該服務器的連接(例如,由于服務器崩潰或關閉),我希望它定期嘗試重新連接,直到成功.

My client application uses a boost::asio::ip::tcp::socket to connect to a remote server. If the app loses connection to this server (e.g. due to the server crashing or being shutdown) I would like it to attempt a re-connect at regular intervals until it succeeds.

我需要在客戶端做什么才能干凈地處理斷開連接、整理然后反復嘗試重新連接?

目前我的代碼中有趣的部分看起來像這樣.

Currently the interesting bits of my code look something like this.

connect是這樣的:

bool MyClient::myconnect()
{
    bool isConnected = false;

    // Attempt connection
    socket.connect(server_endpoint, errorcode);

    if (errorcode)
    {
        cerr << "Connection failed: " << errorcode.message() << endl;
        mydisconnect();
    }
    else
    {
        isConnected = true;

        // Connected so setup async read for an incoming message.
        startReadMessage();

        // And start the io_service_thread
        io_service_thread = new boost::thread(
            boost::bind(&MyClient::runIOService, this, boost::ref(io_service)));
    }
    return (isConnected)
}

runIOServer() 方法只是:

void MyClient::runIOService(boost::asio::io_service& io_service)
{
    size_t executedCount = io_service.run();
    cout << "io_service: " << executedCount << " handlers executed." << endl;
    io_service.reset();
}

如果任何異步讀取處理程序返回錯誤,則它們只需調用此 disconnect 方法:

And if any of the async read handlers return an error then they just call this disconnect method:

void MyClient::mydisconnect(void)
{
    boost::system::error_code errorcode;

    if (socket.is_open())
    {
        // Boost documentation recommends calling shutdown first
        // for "graceful" closing of socket.
        socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, errorcode);
        if (errorcode)
        {
            cerr << "socket.shutdown error: " << errorcode.message() << endl;
        }

        socket.close(errorcode);
        if (errorcode)
        {
            cerr << "socket.close error: " << errorcode.message() << endl;
        }    

        // Notify the observer we have disconnected
        myObserver->disconnected();            
    }

..它嘗試正常斷開連接,然后通知觀察者,觀察者將開始每隔五秒調用 connect() 直到重新連接.

..which attempts to gracefully disconnect and then notifies an observer, which will start calling connect() at five second intervals until it gets reconnected.

還有什么我需要做的嗎?

目前這似乎有效.如果我殺死它所連接的服務器,我會在讀取處理程序中收到預期的 "End of file" 錯誤,并且 mydisconnect() 被調用而沒有任何問題.

Currently this does seem to work. If I kill the server that it is connected to I get the expected "End of file" error at my read handlers and mydisconnect() is called without any issues.

但是當它嘗試重新連接并失敗時,我看到它報告socket.shutdown error: Invalid argument".這僅僅是因為我試圖關閉一個沒有掛起讀/寫的套接字嗎?或者還有什么?

But when it then attempts to re-connect and fails I see it report "socket.shutdown error: Invalid argument". Is this just because I am attempting to shutdown a socket that has no read/writes pending on it? Or is it something more?

推薦答案

每次重新連接時都需要創建一個新的 boost::asio::ip::tcp::socket.最簡單的方法可能是使用 boost::shared_ptr 在堆上分配套接字(如果你的套接字完全封裝在一個類中).例如:

You need to create a new boost::asio::ip::tcp::socket each time you reconnect. The easiest way to do this is probably to just allocate the socket on the heap using a boost::shared_ptr (you could probably also get away with scoped_ptr if your socket is entirely encapsulated within a class). E.g.:

bool MyClient::myconnect()
{
    bool isConnected = false;

    // Attempt connection
    // socket is of type boost::shared_ptr<boost::asio::ip::tcp::socket>
    socket.reset(new boost::asio::ip::tcp::socket(...));
    socket->connect(server_endpoint, errorcode);
    // ...
}

然后,當 mydisconnect 被調用時,你可以釋放套接字:

Then, when mydisconnect is called, you could deallocate the socket:

void MyClient::mydisconnect(void)
{
    // ...
    // deallocate socket.  will close any open descriptors
    socket.reset();
}

您看到的錯誤可能是操作系統在您調用 close 后清理文件描述符的結果.當您調用 close 然后嘗試在同一個套接字上 connect 時,您可能正在嘗試連接無效的文件描述符.此時,根據您的邏輯,您應該會看到一條以Connection failed: ..."開頭的錯誤消息,但您隨后調用了 mydisconnect,這可能是在嘗試調用 shutdown> 在無效的文件描述符上.惡性循環!

The error you're seeing is probably a result of the OS cleaning up the file descriptor after you've called close. When you call close and then try to connect on the same socket, you're probably trying to connect an invalid file descriptor. At this point you should see an error message starting with "Connection failed: ..." based on your logic, but you then call mydisconnect which is probably then attempting to call shutdown on an invalid file descriptor. Vicious cycle!

這篇關于如何在斷開連接后干凈地重新連接 boost::socket?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Assertion failed (size.widthgt;0 amp;amp; size.heightgt;0)(斷言失敗(size.width0 amp;amp; size.height0))
Rotate an image in C++ without using OpenCV functions(在 C++ 中旋轉圖像而不使用 OpenCV 函數)
OpenCV: process every frame(OpenCV:處理每一幀)
Why can#39;t I open avi video in openCV?(為什么我不能在 openCV 中打開 avi 視頻?)
OpenCV unable to set up SVM Parameters(OpenCV 無法設置 SVM 參數)
Convert a single color with cvtColor(使用 cvtColor 轉換單一顏色)
主站蜘蛛池模板: 高低温试验房-深圳高低温湿热箱-小型高低温冲击试验箱-爱佩试验设备 | 复合肥,化肥厂,复合肥批发,化肥代理,复合肥品牌-红四方 | 济南宣传册设计-画册设计_济南莫都品牌设计公司 | 华禹护栏|锌钢护栏_阳台护栏_护栏厂家-华禹专注阳台护栏、楼梯栏杆、百叶窗、空调架、基坑护栏、道路护栏等锌钢护栏产品的生产销售。 | 好看的韩国漫画_韩漫在线免费阅读-汗汗漫画 | 密封圈_泛塞封_格莱圈-[东莞市国昊密封圈科技有限公司]专注密封圈定制生产厂家 | 中开泵,中开泵厂家,双吸中开泵-山东博二泵业有限公司 | 清水混凝土修复_混凝土色差修复剂_混凝土色差调整剂_清水混凝土色差修复_河南天工 | 阳光模拟试验箱_高低温试验箱_高低温冲击试验箱_快速温变试验箱|东莞市赛思检测设备有限公司 | 合肥卓创建筑装饰,专业办公室装饰、商业空间装修与设计。 | 佛山市德信昌电子有限公司| 真空乳化机-灌装封尾机-首页-温州精灌 | 一体化污水处理设备_生活污水处理设备_全自动加药装置厂家-明基环保 | 东莞市海宝机械有限公司-不锈钢分选机-硅胶橡胶-生活垃圾-涡电流-静电-金属-矿石分选机 | 电机铸铝配件_汽车压铸铝合金件_发动机压铸件_青岛颖圣赫机械有限公司 | 双段式高压鼓风机-雕刻机用真空泵-绍兴天晨机械有限公司 | 色谱柱-淋洗液罐-巴罗克试剂槽-巴氏吸管-5ml样品瓶-SBS液氮冻存管-上海希言科学仪器有限公司 | 坏男孩影院-提供最新电影_动漫_综艺_电视剧_迅雷免费电影最新观看 | 超声波成孔成槽质量检测仪-压浆机-桥梁预应力智能张拉设备-上海硕冠检测设备有限公司 | ◆大型吹塑加工|吹塑加工|吹塑代加工|吹塑加工厂|吹塑设备|滚塑加工|滚塑代加工-莱力奇塑业有限公司 | 高温热泵烘干机,高温烘干热泵,热水设备机组_正旭热泵 | 挤出机_橡胶挤出机_塑料挤出机_胶片冷却机-河北伟源橡塑设备有限公司 | 螺旋绞龙叶片,螺旋输送机厂家,山东螺旋输送机-淄博长江机械制造有限公司 | 低温柔性试验仪-土工布淤堵-沥青车辙试验仪-莱博特(天津)试验机有限公司 | 智成电子深圳tdk一级代理-提供TDK电容电感贴片蜂鸣器磁芯lambda电源代理经销,TDK代理商有哪些TDK一级代理商排名查询。-深圳tdk一级代理 | 金刚网,金刚网窗纱,不锈钢网,金刚网厂家- 河北萨邦丝网制品有限公司 | 北京网站建设-企业网站建设-建站公司-做网站-北京良言多米网络公司 | 衬四氟_衬氟储罐_四氟储罐-无锡市氟瑞特防腐科技有限公司 | 地磅-电子地磅维修-电子吊秤-汽车衡-无人值守系统-公路治超-鹰牌衡器 | 耐火浇注料-喷涂料-浇注料生产厂家_郑州市元领耐火材料有限公司 耐力板-PC阳光板-PC板-PC耐力板 - 嘉兴赢创实业有限公司 | 干洗店加盟_洗衣店加盟_干洗店设备-伊蔻干洗「武汉总部」 | HV全空气系统_杭州暖通公司—杭州斯培尔冷暖设备有限公司 | 999范文网_优质范文下载写作帮手| 层流手术室净化装修-检验科ICU改造施工-华锐净化工程-特殊科室建设厂家 | 耐酸泵,耐酸泵厂家-淄博华舜耐腐蚀真空泵 | 亚克力制品定制,上海嘉定有机玻璃加工制作生产厂家—官网 | hdpe土工膜-防渗膜-复合土工膜-长丝土工布价格-厂家直销「恒阳新材料」-山东恒阳新材料有限公司 ETFE膜结构_PTFE膜结构_空间钢结构_膜结构_张拉膜_浙江萬豪空间结构集团有限公司 | 上海宿田自动化设备有限公司-双面/平面/单面贴标机 | 我车网|我关心的汽车资讯_汽车图片_汽车生活! | 杭州成人高考_浙江省成人高考网上报名 | 开平机_纵剪机厂家_开平机生产厂家|诚信互赢-泰安瑞烨精工机械制造有限公司 |