如何模仿插座对在Windows上

2024-09-29 01:29:58 发布

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

不幸的是,标准的Python函数socket.socketpair在Windows上不可用(从python3.4.1开始),我如何编写一个在Unix和Windows上都能工作的替代函数?在


Tags: 函数标准windowsunixsocketsocketpair
2条回答

Python3.5包括对socket.socketpair()的Windows支持。对于python2.7+,可以在PyPi上使用^{} package(我编写的):

import socket
import backports.socketpair

s1, s2 = socket.socketpair()
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

相关问题 更多 >