系统相关
首页 > 系统相关> > C Boost.ASIO:使用Windows API将接受的TCP连接从一个打开的套接字传递到另一个套接字(同时使用Linux API)?

C Boost.ASIO:使用Windows API将接受的TCP连接从一个打开的套接字传递到另一个套接字(同时使用Linux API)?

作者:互联网

我试图学习如何使用Boost.ASIO和Windows API重新分配接受的连接.发现this code sample添加到它包括和使用命名空间所以现在它是可编辑的 – 只需复制和粘贴,在这里你去……“参数不正确”异常在同一个地方代码海报有它=(所以这里是代码:

#include <iostream>
#include <boost/asio.hpp>

#ifdef _WIN32
#include "Windows.h"
#endif

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

int main(){
int m_nPort = 12345;
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), m_nPort));

cout << "Waiting for connection..." << endl;

tcp::socket socket(io_service);
acceptor.accept(socket);
cout << "connection accepted" << endl;

#ifdef _WIN32
WSAPROTOCOL_INFO pi;
WSADuplicateSocket(socket.native(), GetCurrentProcessId(), &pi);
SOCKET socketDup = WSASocket(pi.iAddressFamily/*AF_INET*/, pi.iSocketType/*SOCK_STREAM*/,
                             pi.iProtocol/*IPPROTO_TCP*/, &pi, 0, 0);
char sText[] = "I can use my duplicated socket via WinApi!\r\n";
int nRet = send(socketDup, sText, strlen(sText), 0);
#else
//linux
 int socketDup = dup(socket.native()); // tested on Linux, works!
#endif

try
{
    tcp::socket s(io_service);
    s.assign(tcp::v4(), socketDup); //this throws exception under Windows
    //I can't use my socket via boost lib
    s.send(boost::asio::buffer("Not work\r\n"));
    cout << "We do not get here!=(" << endl;
}
catch(exception &e)
{
    cerr << e.what() << endl; //"The parameter is incorrect" exception
}
cin.get();
}

总的来说,code follows this post和我实际上没有看到有什么问题,如何解决它.

它遵循我们如何将接受的TCP连接从一个进程传递到另一个进程的方式(described here)

可能是this “Socket inheritance on different Windows platforms” example could help,但我不知道如何.

任何人都可以帮我找到任何可能的解决方法吗?

更新:
刚刚在Linux上测试过的代码 – 效果很好,没有错误.

那么Windows版本是什么呢?

解决方法:

尝试使用附加到WSASocket文档的代码片段:

socketDup = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, &pi, 0, WSA_FLAG_OVERLAPPED);

好的,我通过Boost代码进行了跟踪,并且尝试将套接字与I / O完成端口关联起来失败了.那是因为套接字已经与完成端口相关联.

The MSDN docs说:

It is best not to share a file handle associated with an I/O completion port by using either handle inheritance or a call to the DuplicateHandle function. Operations performed with such duplicate handles generate completion notifications. Careful consideration is advised.

知道IOCP与问题有关,我设置(在包括任何boost标头之前)

#define BOOST_ASIO_DISABLE_IOCP 1

一切正常.

本地输出:

Waiting for connection...
connection accepted
We do not get here!=(

远程输出:

I can use my duplicated socket via WinApi!
Not work

标签:c,connection,visual-studio,boost,boost-asio
来源: https://codeday.me/bug/20191007/1865856.html