Friday, May 27, 2011

Writing a Java HTTP Server from scratch

During my second week at 8th Light I was asked to create an HTTP Server to serve TTT games to remote players. That being said, it really had nothing to do with playing TTT, which is a good thing, since the code was architecturally sound enough to place the game logic in a Package named TTTGame and create an independent package named TTTServer. The two packages only cross paths on one occasion, in an abstract class to integrate game logic and web requests.

About five minutes into development I stumbled upon the holy grail, the Sun class com.sun.httpserver. I could bind paths and verbs in different combinations to different handler classes (similar to Rails). Of course, my joy was killed and I was told not to use this class. I had to go forward and build the server from the bottom up.

I started with the essentials (this is Agile after all, I need to build iteratively out from the core). I had experience with Socket programming, although it was a little hazy. So I setup a Server class to wrap around a Server Socket and dish out new Client Sockets as they come in. This was easy enough. From here, I started to run into problems. My experience with Socket programming was to leave a connection open, send data, and close the Socket. Well, this doesn't work for HTTP. I had some learning to do. Namely, I need to learn about HTTP packets and a little refresher on rendering HTML.

The majority of this week was then spent building a Packet class and a Packet Parser class. Initially, I was attempting to build the Packet Parser in a laborious line-by-line fashion. This had to go, it was too painful to write and too ugly to use. Paul put me on the right path, at this point, by implementing the parser recursively. Not only did the LOC drop dramatically, but the class experienced a speed up (which is important with the potential for huge amounts of HTTP packets flying to and from in short amounts of time). I created a utility program to chart the two styles of parsing side by side.


I then wrote my Packet class to nicely integrate with the Parser and voila (as the French say) I had the groundwork of an HTTP Server. Now, I need to add routes based on path (throwing 404 errors when a path isn't valid), and integrating the game logic so a remote user can play.

Finally, the last item on my list of things to do is generate a Session Key for each user on my end and have the user then pass the key in to play their unique game (since we can not keep the Socket connection open throughout the entirety of the game).

Hopefully, I will have a hand made HTTP Java Server up and running in the near future.

No comments:

Post a Comment