OSError:[WinError 10038]尝试对非套接字的操作进行操作

时间:2014-12-08 23:51:08

标签: python sockets

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

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

以下代码给出了我在titile中写的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())

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

1 个答案:

答案 0 :(得分:-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