11

我正在尝试在 Windows 下运行以下 python 服务器:

"""
An echo server that uses select to handle multiple clients at a time.
Entering any line of input at the terminal will exit the server.
"""

import select
import socket
import sys

host = ''
port = 50000
backlog = 5
size = 1024
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host,port))
server.listen(backlog)
input = [server,sys.stdin]
running = 1
while running:
    inputready,outputready,exceptready = select.select(input,[],[])

    for s in inputready:

        if s == server:
            # handle the server socket
            client, address = server.accept()
            input.append(client)

        elif s == sys.stdin:
            # handle standard input
            junk = sys.stdin.readline()
            running = 0

        else:
            # handle all other sockets
            data = s.recv(size)
            if data:
                s.send(data)
            else:
                s.close()
                input.remove(s)
server.close() 

我收到错误消息(10038,'尝试对不是套接字的东西进行操作')。这可能与python 文档中的注释有关“Windows 上的文件对象是不可接受的,但套接字是。在 Windows 上,底层 select() 函数由 WinSock 库提供,并且不处理不接受的文件描述符” t 源自 WinSock。”。在互联网上有很多关于这个主题的帖子,但它们对我来说太技术性或者根本不清楚。所以我的问题是:有什么办法可以在windows下使用python中的select()语句吗?请添加一个小例子或修改我上面的代码。谢谢!

4

3 回答 3

9

看起来不像 sys.stdin

如果您将输入更改为此

input = [server] 

异常会消失。

这是来自文档

 Note:
    File objects on Windows are not acceptable, but sockets are. On Windows, the
 underlying select() function is provided by the WinSock library, and does not 
handle file descriptors that don’t originate from WinSock.
于 2012-05-31T23:54:40.720 回答
5

我不知道您的代码是否还有其他问题,但是您得到的错误是由于传递inputselect.select(),问题是它包含sys.stdin的不是套接字。在 Windows 下,select仅适用于套接字。

附带说明一下,input它是一个 python 函数,将它用作变量并不是一个好主意。

于 2012-05-31T23:57:54.733 回答
0

当然,给出的答案是正确的......你只需要从输入中删除 sys.stdin 但仍然在迭代中使用它:

对于 inputready+[sys.stdin] 中的 s:

于 2017-01-13T23:00:05.403 回答