Skip to main content
 首页 » 编程设计

python之python中的聊天服务器/客户端

2025年05月04日13lhb25

我正在使用这个聊天服务器/客户端 我在尝试运行客户端时遇到了问题 我在 windows 下为该行使用 python 3.4

ready_to_read,ready_to_write,in_error = select.select(socket_list , [], []) 

WinError 10038 尝试对非套接字进行操作

当我将此行 socket_list = [sys.stdin,s] 更改为 socket_list = [s] 时,错误消失但程序不再等待来自客户端的输入

有什么想法吗?

这是代码

# chat_client.py 
 
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 = 'localhost' 
    port = 10000 
 
    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() 
    prompt() 
    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 , [], []) 
 
        for sock in ready_to_read: 
            print('tset') 
            if sock == s: 
                # incoming message from remote server, s 
                data = sock.recv(4096) 
                if not data : 
                    print ('\nDisconnected from chat server') 
                    sys.exit() 
                else : 
                    #print data 
                    sys.stdout.write(data) 
                    sys.stdout.write('[Me] '); sys.stdout.flush()      
 
            else: 
                print('tset') 
                # user entered a message 
                #msg= input() 
                msg = sys.stdin.readline() 
                s.send(msg) 
                sys.stdout.write('[Me] '); sys.stdout.flush()  
 
if __name__ == "__main__": 
 
    sys.exit(chat_client()) 

请您参考如下方法:

引自select doc

Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.

可能是windows的限制问题。

编辑:

这确认了 Windows 上的问题:

select.select(rlist, wlist, xlist[, timeout])

Empty sequences are allowed, but acceptance of three empty sequences is platform-dependent. (It is known to work on Unix but not on Windows.)

您应该看到文档的注释部分,其中提供了 WinSock 库的解决方法: https://docs.python.org/2/library/select.html?highlight=select#select.select