无法使用ERROR_INVALID_HANDLE(6)关闭套接字句柄

时间:2018-04-19 07:57:22

标签: python windows-ce ctypes winsock2

我在ctypes中使用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 个答案:

答案 0 :(得分:2)

HANDLE SOCKET 是不同类型的对象,因此它们不兼容(适用于 Python >包装纸。)

这里有[MS.Docs]: CloseHandle function个州:

  

请勿使用 CloseHandle 功能关闭套接字。相反,使用closesocket函数,它释放与套接字关联的所有资源,包括套接字对象的句柄。有关详细信息,请参阅Socket Closure

<强> @ EDIT0

作为一个附带问题:为什么使用 ctypes 而不是[Python 3]: socket - Low-level networking interface这是 WinSock 的包装?这就像在脚下射击自己一样。如果 BT 套接字与其他套接字(例如网络)的工作方式相同,那么您唯一需要做的就是定义一些常量(例如 BTHPROTO_RFCOMM )。