Reputation: 51
I am working on a simple chat app in python 3.6.1 for personal use. I get this error with select.select:
Traceback (most recent call last):
File "C:\Users\Nathan Glover\Google Drive\MAGENTA Chat\chat_server.py", line
27, in <module>
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
ValueError: file descriptor cannot be a negative integer (-1)
Here is the code:
ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)
This is entirely because i don't understand select very well, and the documentation was no help. Could someone explain why this is happening?
Upvotes: 5
Views: 10143
Reputation: 1
It is because one of the file descriptors is a negative value. To fix this Check if the file desc is negative and remove it from the list.
for sock in SOCKET_LIST:
if sock.fileno() == -1:
SOCKET_LIST.remove(sock)
ready_read, ready_write, error = sel.select(SOCKET_LIST, [], [], 0)
Upvotes: 0
Reputation: 429
It might not work if you did not properly initialize your server socket. Try this code:
HOST = '127.0.0.1' # '' = all available interfaces
PORT = 9009 # Arbitrary non-privileged port
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(0) # non-blocking I/O
sock.bind((HOST, PORT))
sock.listen(5) # queue up as many as 5 connect requests
SOCKET_LIST = [sock]
Upvotes: 0
Reputation: 11
I happened to have this problem too, and I have solved it. I hope this answer will help everyone. The fileno of the closed socket will become -1. So it is most likely because there is a closed socket in the input parameter list of slelect. That is to say, in the select cycle, when your judgment logic is added to rlist, wlist, xlist, these logics may be problematic. Although the simple and crude method is try-except to remove the socket with negative fileno. But I recommend that you reorganize your logic. If you are not sure, use rlist, wlist, and xlist instead of lists to avoid duplicate elements in the list.
Upvotes: 1
Reputation: 440
I know it's been a long time since this question was asked. But I wanted to let OP and others know about the problem here. The problem here is that the SOCKET_LIST must be containing a non-existing socket connection which may have been disconnected earlier. If you pass such connection to select it gives this error
ValueError: file descriptor cannot be a negative integer (-1)
A simple solution to this would be to put the select
block inside a try - except block and the catch the error. When an error is found, the connection can be removed from the SOCKET_LIST.
Upvotes: 8