gpt4 book ai didi

python - 无法通过 ERROR_INVALID_HANDLE 关闭套接字句柄 (6)

转载 作者:行者123 更新时间:2023-12-01 01:58:35 25 4
gpt4 key购买 nike

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

最佳答案

HANDLESOCKET是不同类型的对象,因此它们不兼容(适用于它们的Python> wrapper 也是如此)。

这就是 [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)。

关于python - 无法通过 ERROR_INVALID_HANDLE 关闭套接字句柄 (6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49915698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com