Hi everyone, I am in the process of learning how to use select to run a server that can handle multiple clients. I have not been able to find any server examples which implement Try/Catch Exception errors, which I believe is the root of my problems.
Basically the server works fine by receiving a message from the client, prints it to the screen, then apparently will know a client has disconnected by not receiving any bytes from him. When I close my client, the server throws a 10054 error message: "An existing connection was forcibly closed by the remote host".
I THINK this is just the server telling me that the client socket has been closed by means not related to the server actually running socket.close() which is true... How can I get it to do this cleanly without crashing the server?
Here is my code: I pride myself on decent code structure so you shouldn't have much trouble figuring out what is going on.
import socket import select # Server attributes HOST = '' # Host address PORT = 6006 # Host port BACKLOG = 5 # Number of queued connections BUFFER = 1024 # Data buffer size # Initialize server server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((HOST, PORT)) server.listen(BACKLOG) clients =  # Container for all open sockets while True: inputready, outputready, errors = select.select( [server] + clients, ,  ) for socket in inputready: if socket == server: # Handle server socket client, address = server.accept() print "Received a connection from ", address clients.append(client) else: # Handle all other sockets data = socket.recv(BUFFER) if data: print "Received:", data else: socket.close() clients.remove(client)
import socket # Client attributes HOST = 'localhost' # Host address PORT = 6006 # Host port BUFFER = 1024 # Data buffer size # Initialize server connection mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mySocket.connect((HOST, PORT)) mySocket.send("I have connected!") print mySocket.recv(BUFFER) mySocket.close()
Another thing I could use help on if you are feeling nice - it only crashes when I hit the "X" on the client program. If I uncomment the last line on the client, it will still crash, but the server doesn't crash right away even when I thought it was going to because it is closing the socket. Why?