2011-03-16 33 views
2

我想了解如何使用Boost.ASIO和Windows API重新分配接受的连接。发现this code sample添加到它包括和使用命名空间,所以现在它是可编译的 - 只需复制和粘贴,在这里你去...“参数不正确”异常在同一地方代码海报了它=(所以这里是代码:C++ Boost.ASIO:使用Windows API将已接受的TCP连接从一个打开的套接字传递给另一个套接字(同时适用于Linux API)?

#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版本是什么?

+0

[offtopic] ..片刻我想知道什么提振寝食不安业务内容在做(HTTP://en.wikipedia .org/wiki/Australian_Security_Intelligence_Organisation)而不是编译器业务(http://www.boost.org/doc/libs/1_41_0/doc/html/boost_asio.html) – 2011-03-16 14:44:33

回答

4

尝试使用连接到 WSASocket文件的代码片段:

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


好吧,我通过升压码追踪和失败尝试在套接字与关联I/O完成端口。这是因为套接字已经关联到完成端口。

The MSDN docs说:

最好不要通过使用处理继承或到DuplicateHandle函数调用共享的I/O完成端口相关联的文件句柄。用这种重复句柄执行的操作会生成完成通知。建议仔细考虑。

明知IOCP相关的问题,我设置(包括任何刺激头前)

#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 
+0

嗯......试过了 - 似乎是同样的错误.. =(你试过了吗?它在你的机器上工作吗? – Rella 2011-03-16 18:01:57

+1

@Blender:我的工作机器上没有安装升压。当我回家时,我可以尝试编译你的文件。 – 2011-03-16 18:15:46

+0

我不会理睬!等待你的帮助。 – Rella 2011-03-16 18:19:47

相关问题