Handling net_read() blocking or disposing threads
June 13, 2011 09:39AM
I created a thread on the [devkitpro.org] forums 3 days ago with no response but those forums are slow so I thought I'd try here as well.

I'm writing an ftp server and I've run into a problem. If the client waits too long between messages, I want to end the connection but I can't figure out a way to do that. As of now my program is set up like this:

1. Main thread (for controller input) spawns a server thread
2. Server thread listens for new connections and spawns threads for new clients
3. Client threads run net_read() in a loop, which blocks until data is received; the loop finally broken when the client closes the connection:

	while ((recv = net_read(client->sock, buffer + offset, __CMD_RECV_BUFFER - offset)) > 0) {
		// process data
	}

	net_close(client->sock);


Since net_read() blocks, I can't tell from within the client threads if I should end the connection unless more data comes in so the function unblocks, which could be never. So my solution was to create a watchdog thread that will periodically check to see when the last time data was received in each child thread, and if it was more than X minutes ago, net_close() the socket and "delete" the thread. But I can't seem to find a function to completely get rid of the thread, only to suspend it, unless it exits on its own.

Is there such a function? If not, what would be the most elegant solution?



Edited 2 time(s). Last edit at 06/13/2011 11:52PM by todd.
Re: Handling net_read() blocking or disposing threads
June 13, 2011 01:45PM
Why doesn't the thread "exit on its own" after net_read returns an error (after the watchdog thread closes the socket)?
Re: Handling net_read() blocking or disposing threads
June 13, 2011 09:26PM
No idea, but I've tried that too. I can open a telnet session to the FTPd from my PC, net_close() it from the Wii, telnet says it lost the connection on my PC, and net_read doesn't unblock/return an error until I actually close the telnet window on my PC.

Someone actually responded to my other thread on devkitpro with a tip for using nonblocking sockets, so I think I'll give that a try.



Edited 1 time(s). Last edit at 06/13/2011 09:26PM by todd.
Re: Handling net_read() blocking or disposing threads
June 14, 2011 01:49AM
Ah. You could try using net_shutdown instead of net_close in the watchdog thread.
Instead of non-blocking sockets you could use net_poll. It's very powerful, allows you to do a timed/infinite wait for activity on an array of sockets and would remove the need for individual threads completely.
You could also try setting SO_KEEPALIVE on your sockets so they'll get closed after a while if the connection drops out.
Sorry, only registered users may post in this forum.

Click here to login