Skip to main content
 首页 » 编程设计

python之操作系统错误 : [WinError 10038] An operation was attempted on something that is not a socket

2025年05月04日8grandyang

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

服务器端和客户端使用相同的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()) 

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

请您参考如下方法:

        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 :

… Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types …

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