【问题标题】:OSError: [WinError 10038] An operation was attempted on something that is not a socketOSError:[WinError 10038] 尝试对非套接字的操作进行操作
【发布时间】:2015-02-06 18:23:27
【问题描述】:

我在这里测试了一个客户端方案

服务器和客户端使用相同的 9009 端口进行连接

不知何故,下面的代码给了我标题中写的 OSError:

import sys
import socket
import select

def chat_client():
    if(len(sys.argv) < 3) :
        print ('Usage : python chat_client.py hostname port')
        sys.exit()

    host = sys.argv[1]
    port = int(sys.argv[2])

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)

    # connect to remote host
    try :
        s.connect((host, port))
    except :
        print ('Unable to connect')
        sys.exit()

    print ('Connected to remote host. You can start sending messages')
    sys.stdout.write('[Me] '); sys.stdout.flush()

    while 1:
        socket_list = [sys.stdin, s]

        # Get the list sockets which are readable
        ready_to_read,ready_to_write,in_error = select.select(socket_list,[],[])
        # the timeout argument is omitted in above code,so chat_client blocks until a fd is ready
        for sock in ready_to_read:             
            if sock == s:
                # incoming message from remote server, s
                data = sock.recv(4096)   # sock.recv argument is buffsize, recommend 4096
                if not data :            # if not (data is not none), data is empty
                    print ('\nDisconnected from chat server')
                    sys.exit()
                else :                   # data has something
                    #print data
                    sys.stdout.write(data)   # write something to standard output buffer
                    sys.stdout.write('[Me] '); sys.stdout.flush() # write everything to terminal from buffer

            else :     # sock ! = s
                # user entered a message
                msg = sys.stdin.readline()    # readline pick up everything from stdin
                s.send(msg)
                sys.stdout.write('[Me] '); sys.stdout.flush() 

if __name__ == "__main__":

  sys.exit(chat_client())

任何人都可以给我一些提示吗? :)

【问题讨论】:

  • 我在 PyCharm 中从 cmd 运行烧瓶时出现此错误。切换到Windows CMD窗口,错误消失了。

标签: python sockets


【解决方案1】:
        socket_list = [sys.stdin, s]

        # Get the list sockets which are readable
        ready_to_read,ready_to_write,in_error = select.select(socket_list,[],[])

Python » Documentation » The Python Standard Library » 16. Optional Operating System Services » 16.1. select — Waiting for I/O completion:

... 请注意,在 Windows 上,它仅适用于套接字;在其他操作 系统,它也适用于其他文件类型……

因此,与健全的操作系统不同,我们不能在这里使用sys.stdin

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 2021-09-01
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    相关资源
    最近更新 更多