代码之家  ›  专栏  ›  技术社区  ›  Ben

无法关闭套接字句柄,错误为\u INVALID\u handle(6)

  •  1
  • Ben  · 技术社区  · 6 年前

    我正在C类型中使用winsock2套接字,我可以 closesocket() 很好,但是调用CloseHandle,总是会导致 ERROR_INVALID_HANDLE (6) .我应该如何正确关闭它?当前,我的应用程序总是在64次socket()调用后崩溃。

    # from MSDN:
    # BOOL CloseHandle(   HANDLE hObject);
    
    closehandle = coredll.CloseHandle
    closehandle.argtypes = [ w.LPVOID ]
    
    SOCKET = c_ulong
    socket = ws2.socket
    socket.restype = SOCKET
    self._clnt_socket = socket(AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM)
    ...
    connect( self._clnt_socket, _psa, sizeof(self._sa) )
    ...
    send( self._clnt_socket, pbuff, szbuff, 0 ) # int send(  SOCKET s,  const char FAR* buf,  int len,  int flags);
    
    SetLastError(0)
    rt = closesocket( self._clnt_socket )
    ec = GetLastError()
    if ec != w.ERROR_SUCCESS :
        print( u'failed to close socket, ec=%s, %s, rt=%s', (ec, FormatError( ec ), rt) )
        raise Exception(u'BT_SOCKET.close.socket %s' % ec)
    else:
        print( u'close socket ok' )
    #> close socket ok
    
    # from MSDN:
    # To close the connection to the target device, call the closesocket
    # function to close the Bluetooth socket. Also, ensure that you release
    # the socket by calling the CloseHandle function, as the following
    # example code shows.  
    #
    # closesocket(client_socket); 
    # CloseHandle((LPVOID)client_socket);
    
    SetLastError(0)
    rt = closehandle(  w.LPVOID( self._clnt_socket ) )
    ec = GetLastError()
    if ec != w.ERROR_SUCCESS :
        print( u'failed to close handle, ec=%s, %s, rt=%s ', (ec, FormatError( ec ), rt) )
        # //Perform error handling.
        raise Exception(u'BT_SOCKET.close.handle %s' % ec)
    else:
        print( u'close socket ok' )
    #> failed to close handle, ec=6
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   CristiFati    5 年前

    手柄 s和 插座 s是不同类型的 对象 ,因此它们不兼容(适用于 python 包装器)。

    这里是什么 [MS.Docs]: CloseHandle function 国家:

    请勿使用 关闭手柄 函数关闭插座。相反 使用 closesocket 作用 ,它释放与套接字关联的所有资源,包括套接字对象的句柄。有关更多信息,请参阅 Socket Closure

    @编辑0 :

    作为一个附带问题:为什么要使用 C类型 而不是 [Python 3]: socket - Low-level networking interface 这是一个包裹 WinSock公司 ?这就像在脚上开枪一样。如果 英国电信 套接字的工作方式与其他套接字(例如网络)相同,您只需定义一些常量(例如。 BTHPROTO\U RFCOMM )。