Showing posts from October, 2009

Setting Java Socket Timeouts

Oddly, Java's Socket library doesn't allow you to set the socket timeout directly in the constructor. Its important to note that there is no default so the socket will last forever (ish). Note: The socket timeouts below apply to different situations: setSoTimeout applies to read timeouts. connect applies to connection establishment. At least that's how I read it. I found two options, setting the option on the socket after creating one simplest (for me at least): Socket s; try { s = new Socket( ip, port ); s.setSoTimeout( secs * 1000 ); // converts secs to ms // do other stuff like get input stream and read it } catch ( SocketException se ) { // catch timeout or other socket related error } catch ( Exception e ) { // any other exception } The other option is creating a Socket object without any parameters then calling the connect method with timeout. Here is a rough prototype since it seemed like pain to me but I was curious about the code: Socket s = new Socket

A journey through whitespace cleanup - Perl5 and split

Running through some older Perl5 code, I found someone using grep with a split to cleanup white space on some incoming data. Found, this seemed confusing to me with lots of extra complexity: my @line = grep { s/\s*$// } split /\|/, $_; First Pass: my @line = split /\|\s*/, $_; But my guess is that all wrapping white space should be removed: my @line = split /\s*\|\s*/, $_; Even better (and more readable), use the Perl magic context: my @line = split /\s*\|\s*/; I would love to make that a cleaner regex but that will have to be another day...