如何在 Windows 上模拟 socket.socketpair [英] How to emulate socket.socketpair on Windows
本文介绍了如何在 Windows 上模拟 socket.socketpair的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
标准的 Python 函数 socket.socketpair 不幸的是不是在 Windows 上可用(从 Python 3.4.1 开始),我如何编写一个可以在 Unix 和 Windows 上运行的替代品?
The standard Python function socket.socketpair is unfortunately not available on Windows (as of Python 3.4.1), how can I write a replacement that works on both Unix and Windows?
推荐答案
import socket
import errno
def create_sock_pair(port=0):
"""Create socket pair.
If socket.socketpair isn't available, we emulate it.
"""
# See if socketpair() is available.
have_socketpair = hasattr(socket, 'socketpair')
if have_socketpair:
client_sock, srv_sock = socket.socketpair()
return client_sock, srv_sock
# Create a non-blocking temporary server socket
temp_srv_sock = socket.socket()
temp_srv_sock.setblocking(False)
temp_srv_sock.bind(('', port))
port = temp_srv_sock.getsockname()[1]
temp_srv_sock.listen(1)
# Create non-blocking client socket
client_sock = socket.socket()
client_sock.setblocking(False)
try:
client_sock.connect(('localhost', port))
except socket.error as err:
# EWOULDBLOCK is not an error, as the socket is non-blocking
if err.errno != errno.EWOULDBLOCK:
raise
# Use select to wait for connect() to succeed.
import select
timeout = 1
readable = select.select([temp_srv_sock], [], [], timeout)[0]
if temp_srv_sock not in readable:
raise Exception('Client socket not connected in {} second(s)'.format(timeout))
srv_sock, _ = temp_srv_sock.accept()
return client_sock, srv_sock
这篇关于如何在 Windows 上模拟 socket.socketpair的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文