简体   繁体   English

从Boost.ASIO的套接字类中分离本机套接字

[英]Detaching a native socket from Boost.ASIO's socket class

Is it possible to detach a native socket from Boost.ASIO's socket class? 是否可以从Boost.ASIO的套接字类中分离本机套接字? If so, how can it be done? 如果是这样,怎么办呢? I can't seem to find anything obvious in the documentation. 我似乎无法在文档中找到任何明显的东西。

As a quick overview of what I'm trying to accomplish: I have a class that makes a connection and does some negotiation using Boost.ASIO, then passes back a native Windows SOCKET on success or 0 on failure. 快速概述我正在尝试完成的任务:我有一个使用Boost.ASIO进行连接并进行协商的类,然后在成功时传回本机Windows SOCKET或在失败时传回0。

Unless I'm mistaken, the native socket will be closed and deallocated when my boost::asio::basic_socket is destructed. 除非我弄错了,否则当我的boost :: asio :: basic_socket被破坏时,本机套接字将被关闭并释放。

Answering my own question. 回答我自己的问题。

Windows has a WSADuplicateSocket function, which can be used to duplicate the native socket. Windows有一个WSADuplicateSocket函数,可用于复制本机套接字。 The underlying socket will remain open until all descriptors for this socket are deallocated. 底层套接字将保持打开状态,直到释放此套接字的所有描述符。

http://msdn.microsoft.com/en-us/library/ms741565(VS.85).aspx http://msdn.microsoft.com/en-us/library/ms741565(VS.85).aspx

For Mac OS X do the following (for Linux it isn't hard to modify, just notice the very idea): 对于Mac OS X,请执行以下操作(对于Linux,不难修改,只需注意这个想法):

  1. Wrap socket in a shared_ptr , so that it won't close when passing into different routines and keep it alive (at least one reference should always exist); shared_ptr包装套接字,以便在传入不同的例程时不会关闭并使其保持活动状态(至少应该存在一个引用);
  2. Get a native descriptor with socket.native(); 使用socket.native();获取本机描述符socket.native();
  3. Remove it from kqueue: 从kqueue中删除它:

     struct kevent event; EV_SET(&event, descriptor, EVFILT_READ, EV_DELETE, 0, 0, 0); //or EVFILT_WRITE 
  4. And make it blocking if needed: 并在需要时使其阻止:

     fcntl(descriptor, F_SETFL, fcntl(descriptor, F_GETFL, 0) & ~O_NONBLOCK); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM