无法关闭套接字句柄,错误为“无效的”句柄(6)

2024-07-05 10:55:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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

Tags: thetoselfcloseerrorsocketprintrt
1条回答
网友
1楼 · 发布于 2024-07-05 10:55:05

它们的和的类型是不兼容的。在

以下是[MS.Docs]: CloseHandle function状态:

Do not use the CloseHandle function to close a socket. Instead, use the closesocket function, which releases all resources associated with the socket including the handle to the socket object. For more information, see Socket Closure.

@EDIT0

作为附带问题:为什么要使用ctypes而不是[Python 3]: socket - Low-level networking interface,后者是WinSock的包装器?这就像是朝自己的脚开枪。如果BT套接字的工作方式与其他套接字相同(例如网络),那么您只需定义一些常量(例如BTHPROTO懔RFCOMM)。在

相关问题 更多 >