Xsocket
267 wordsI’ve written a fair few TCP/IP servers in my time. In C, always based around the accept() and fork() model. In Java, both using the similar accept()/Thread.start() model, and with the schmancy NIO select() approach.
Now, really, most of us don’t have to worry about the massive loads that make process spawning overheads or thread limits an issue, but it’s still nice to feel you’re being as efficient as possible. On the other hand, if you go single-threaded, there’s a real risk that one expensive operation will affect every single connection.
Really, you want something in between, with more than one thread, but some sharing of threads between connections. This is what all the highly optimised Web and application servers do. Look into actually writing this yourself though, and you’ll soon find that it’s a heavier task than your purpose can really merit.
I hear all the application server users crying “don’t reinvent the wheel”. They’re right. But in most cases they’re only thinking about HTTP. Highly optimised HTTP servers are ten-a-penny in loads of languages on loads of platforms. For example Grizzly lets you delve into the documentation quite a way before you realise that it’s very HTTP oriented indeed.
So it was with delight that I found xSocket, with which an ‘echo’ server with all those performance bells and whistles would be about 8 lines of code.
Every paragraph of the tutorial introduces something that makes me think “ooh, that’s handy”. And if you feel really fruity, you can implement the handlers in jRuby or Jython. Or Groovy. New one on me, that.
I’ll be using it next chance I get.
November 30th, 2007 at 15:31
That looks pretty handy, certainly saving a lot of boiler plate socket handling code. Spinning off lots of threads is always an interesting one. It’s rarely a good idea to have no bounds on the number active threads. C# has a very handy threadpool and I assume Java does too (though I haven’t looked yet). I guess most of the socket code I’ve written in the past has been read only (and for small amounts of data) since I’ve always gone for the read, sling on a queue approach then have multiple threads reading from the queue. This has worked well in the past for things like price ticks where the amount of data is tiny but the volume of small ticks is immense. It also allows you to throw away subsequent ticks for the same stock if you have an unprocessed tick in the ‘queue’
Hmmm went a little off track there