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 轉換單一顏色)
主站蜘蛛池模板: 安徽净化工程设计_无尘净化车间工程_合肥净化实验室_安徽创世环境科技有限公司 | 专业音响设备_舞台音响设备_会议音响工程-首选深圳一禾科技 | 塑料瓶罐_食品塑料瓶_保健品塑料瓶_调味品塑料瓶–东莞市富慷塑料制品有限公司 | 紫外荧光硫分析仪-硫含量分析仪-红外光度测定仪-泰州美旭仪器 | 上海橡胶接头_弹簧减震器_金属软接头厂家-上海淞江集团 | 玻纤土工格栅_钢塑格栅_PP焊接_单双向塑料土工格栅_复合防裂布厂家_山东大庚工程材料科技有限公司 | 隐形纱窗|防护纱窗|金刚网防盗纱窗|韦柏纱窗|上海青木装潢制品有限公司|纱窗国标起草单位 | 北京企业宣传片拍摄_公司宣传片制作-广告短视频制作_北京宣传片拍摄公司 | 多物理场仿真软件_电磁仿真软件_EDA多物理场仿真软件 - 裕兴木兰 | 一技任务网_有一技之长,就来技术任务网| OLChemim试剂-ABsciex耗材-广州市自力色谱科仪有限公司 | 盘式曝气器-微孔曝气器-管式曝气器-曝气盘-斜管填料 | 郑州市前程水处理有限公司 | 托盘租赁_塑料托盘租赁_托盘出租_栈板出租_青岛托盘租赁-优胜必达 | 冷热冲击试验箱_温度冲击试验箱价格_冷热冲击箱排名_林频厂家 | 高压无油空压机_无油水润滑空压机_水润滑无油螺杆空压机_无油空压机厂家-科普柯超滤(广东)节能科技有限公司 | 万濠投影仪_瑞士TRIMOS高度仪_尼康投影仪V12BDC|量子仪器 | 钣金加工厂家-钣金加工-佛山钣金厂-月汇好 | 熔体泵_熔体出料泵_高温熔体泵-郑州海科熔体泵有限公司 | 领先的大模型技术与应用公司-中关村科金| 济南画室培训-美术高考培训-山东艺霖艺术培训画室 | 苏州教学设备-化工教学设备-环境工程教学模型|同科教仪 | 美的商用净水器_美的直饮机_一级代理经销商_Midea租赁价格-厂家反渗透滤芯-直饮水批发品牌售后 | 818手游网_提供当下热门APP手游_最新手机游戏下载 | 钢绞线万能材料试验机-全自动恒应力两用机-混凝土恒应力压力试验机-北京科达京威科技发展有限公司 | 嘉兴恒升声级计-湖南衡仪声级计-杭州爱华多功能声级计-上海邦沃仪器设备有限公司 | PCB接线端子_栅板式端子_线路板连接器_端子排生产厂家-置恒电气 喷码机,激光喷码打码机,鸡蛋打码机,手持打码机,自动喷码机,一物一码防伪溯源-恒欣瑞达有限公司 假肢-假肢价格-假肢厂家-河南假肢-郑州市力康假肢矫形器有限公司 | 工业插头-工业插头插座【厂家】-温州罗曼电气 | 北京工业设计公司-产品外观设计-产品设计公司-千策良品工业设计 北京翻译公司-专业合同翻译-医学标书翻译收费标准-慕迪灵 | 专业深孔加工_东莞深孔钻加工_东莞深孔钻_东莞深孔加工_模具深孔钻加工厂-东莞市超耀实业有限公司 | 氧化锆纤维_1800度高温退火炉_1800度高温烧结炉-南京理工宇龙新材料股份有限公司 | 圣才学习网-考研考证学习平台,提供万种考研考证电子书、题库、视频课程等考试资料 | 石家庄装修设计_室内家装设计_别墅装饰装修公司-石家庄金舍装饰官网 | X光检测仪_食品金属异物检测机_X射线检测设备_微现检测 | 动物麻醉机-数显脑立体定位仪-北京易则佳科技有限公司 | 酒精检测棒,数显温湿度计,酒安酒精测试仪,酒精检测仪,呼气式酒精检测仪-郑州欧诺仪器有限公司 | ORP控制器_ORP电极价格-上优泰百科| 滚筒烘干机_转筒烘干机_滚筒干燥机_转筒干燥机_回转烘干机_回转干燥机-设备生产厂家 | 继电器模组-IO端子台-plc连接线-省配线模组厂家-世麦德 | 防堵吹扫装置-防堵风压测量装置-电动操作显示器-兴洲仪器 | 温州中研白癜风专科_温州治疗白癜风_温州治疗白癜风医院哪家好_温州哪里治疗白癜风 | 奇酷教育-Python培训|UI培训|WEB大前端培训|Unity3D培训|HTML5培训|人工智能培训|JAVA开发的教育品牌 |