Blog
Series
Videos
Talks

Multiplayer tic-tac-toe in Java using Netty (NIO)

2nd of November, 2011

What does this game of tic-tac-toe and Twitter have in common? Both have been implemented using relatively the same technologies: Java and Netty. It was big news in 2010 when Twitter migrated their search from Ruby on Rails to Java-based Netty (read about it here). Not only was it big in the news department, but it was also big in the results department: Twitter reported their search performance increased by 3x.

What is Netty?

Netty is a client server framework by JBoss that simplifies network programming. Netty is built on top of Java NIO but provides a much more simple API to work with. Netty can be used to build a custom server for network communications; it can be used to build anything including a lightweight HTTP server, a TCP / UDP server, a WebSocket server, or any other network server you can dream of. Because Netty is built on Java NIO, Netty’s programming model is asynchronous. This means Netty is very well suited for any number of bi-directional communication projects such as real-time group chat or anything else requiring the server to push information to a client rather than other methods of network communication such as long-polling.

What is the WebSocket protocol?

WebSocket is a protocol used for bi-directional asynchronous communications between a client (usually a web browser) and a server that supports the WebSocket protocol.

A WebSocket client connects to a server via standard HTTP and performs a handshake, which creates a persistent tunnel between the client and server. After the handshake is performed the client and the server communicate freely using a message/event-driven programming model (binding actions/methods to events). The beautiful thing about the WebSocket protocol is the number of persistent connections that WebSocket servers can handle, easily numbering in the ten-of-thousands, and the volume of messages that can be processed (depending on the way the server is implemented).

Netty in action: a game of tic-tac-toe

Rather than build the same-old group chat application everyone else does to show off the flexibility of Netty and the WebSocket protocol, I decided to build a simple game of tic-tac-toe instead. It seems like an odd decision considering tic-tac-toe is a turn-based game rather than a real-time game, but most tic-tac-toe game demos on the net are single-player. Rather than build another single player game of tic-tac-toe, let’s build a multiplayer game!

The core concepts behind the game are:

If you’d like to review the full code for the working Netty tic-tac-toe client and server before reading ahead, feel free to check it out:

Building the Netty server

The first step to creating our tic-tac-toe server is to build the server itself. Creating a new server in Netty is dead simple. We simply need to instruct Netty which port to bind to and which pipeline factory to use.

Netty works based on inbound and outbound “handlers”; upstream handlers and downstream handlers. As a message is either received by the server or sent by the server, it is acted upon by the handlers that you specify in the pipeline factory. This is a flexible architecture and lets us work in a very modular fashion on any given message. Anyone who has done MDB, MQ, or SOAP programming (SOAP handler chain) should be familiar with the concept already.

 1public class TicTacToeServer {
 2	public static void main(String[] args) throws Exception {
 3	    ChannelFactory factory =
 4	    new NioServerSocketChannelFactory(
 5	        Executors.newCachedThreadPool(),
 6	        Executors.newCachedThreadPool());
 7	    ServerBootstrap bootstrap = new ServerBootstrap(factory);
 8	    bootstrap.setPipelineFactory(new WebSocketServerPipelineFactory());
 9	    bootstrap.setOption("child.tcpNoDelay", true);
10	    bootstrap.setOption("child.keepAlive", true);
11	    bootstrap.bind(new InetSocketAddress(9000));
12	    System.out.println("TicTacToe Server: Listening on port 9000");
13	}
14}

The next step is creating the pipeline factory. In this case we’re using a custom pipeline factory called WebSocketServerPipelineFactory. We could also have built this as an anonymous class as our implementation is fairly simple, but I decided to break it out into it’s own high-level class.

 1public class WebSocketServerPipelineFactory implements ChannelPipelineFactory {  
 2    public ChannelPipeline getPipeline() throws Exception {  
 3        ChannelPipeline pipeline = pipeline();  
 4        pipeline.addLast("decoder", new HttpRequestDecoder());  
 5        pipeline.addLast("aggregator", new HttpChunkAggregator(65536));  
 6        pipeline.addLast("encoder", new HttpResponseEncoder());  
 7        pipeline.addLast("handler", new TicTacToeServerHandler());  
 8        return pipeline;  
 9    }
10}

Take a second to look at the above code. I’ll break out some of the key terms and concepts to understand:

Channel

A channel is a persistent connection (tunnel) from a specific client to the server.

ChannelPipeline

Each channel can be customized with it’s own pipeline. When you take a second to think about it, it becomes obvious how powerful this concept is. Encoders, decoders, aggregator, and handlers are grouped together to form a pipeline. A pipeline instructs Netty how to act on each channel.

Encoders, decoders, and aggregators

Netty is a low-level framework built on Java NIO. When a client first connects with the server, we need to perform a WebSocket handshake. NIO doesn’t care about HTTP however, it cares about packets. In order to process the HTTP request and response, we need to instruct Netty how to deal with the packets we’re receiving and sending. Netty makes this easy and provides multiple encoders, decoders, aggregator, and handlers. We’ll typically extend Netty to create our own custom handlers, but if we’re so inclined, we can also get really low-level and create our own encoders, etc. Keep in mind that handlers can be swapped-out at runtime. After the initial HTTP handshake is performed, we’re only going to be responding to WebSocket requests for this channel. You’ll see later how we change from an HTTP-based pipeline to a WebSocket-based pipeline for a specific channel (aka client, aka player).

TicTacToeServerHandler

This is the heart of the application, responsible for consuming and pushing all messages to and from clients. An instance of this handler is specific to a channel, but we can also declare static variables to keep track of all the games of tic-tac-toe in progress at any given time.

Let’s check out the TicTacToeServerHandler. I’ll discuss some of the core concepts below.

1@Override  
2public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {  
3    Object msg = e.getMessage();  
4    if (msg instanceof HttpRequest) {  
5        handleHttpRequest(ctx, (HttpRequest) msg);  
6    } else if (msg instanceof WebSocketFrame) {
7	    handleWebSocketFrame(ctx, (WebSocketFrame) msg);  
8	}
9}

The messageReceived(…) method is the main callback method provided by Netty to process incoming messages from clients. In our case, we’ll only be processing two types of messages: HttpRequest (for the initial handshake from a client) and WebSocketFrame (for all incoming communications after the tunnel has been established).

 1private void handleHttpRequest(ChannelHandlerContext ctx, HttpRequest req) throws Exception {
 2	// Allow only GET methods.
 3	if (req.getMethod() != HttpMethod.GET) {
 4	    sendHttpResponse(ctx, req, new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
 5	    return;
 6	}
 7	
 8	// Serve the WebSocket handshake request.
 9	if (req.getUri().equals(WEBSOCKET_PATH) && Values.UPGRADE.equalsIgnoreCase(req.getHeader(CONNECTION)) && WEBSOCKET.equalsIgnoreCase(req.getHeader(Names.UPGRADE))) {
10	// Create the WebSocket handshake response.
11	    HttpResponse res = new DefaultHttpResponse(HTTP_1_1, new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
12	    res.addHeader(Names.UPGRADE, WEBSOCKET);
13	    res.addHeader(CONNECTION, Values.UPGRADE);
14	
15	    // Fill in the headers and contents depending on handshake method. New handshake specification has a challenge.
16	    if (req.containsHeader(SEC_WEBSOCKET_KEY1) && req.containsHeader(SEC_WEBSOCKET_KEY2)) {
17	        // New handshake method with challenge
18	        res.addHeader(SEC_WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
19	        res.addHeader(SEC_WEBSOCKET_LOCATION, getWebSocketLocation(req));
20	        String protocol = req.getHeader(SEC_WEBSOCKET_PROTOCOL);
21	
22	        if (protocol != null) {
23	            res.addHeader(SEC_WEBSOCKET_PROTOCOL, protocol);
24	        }
25	
26	        // Calculate the answer of the challenge.
27	        String key1 = req.getHeader(SEC_WEBSOCKET_KEY1);
28	        String key2 = req.getHeader(SEC_WEBSOCKET_KEY2);
29	        int a = (int) (Long.parseLong(key1.replaceAll("[^0-9]", "")) / key1.replaceAll("[^ ]", "").length());
30	        int b = (int) (Long.parseLong(key2.replaceAll("[^0-9]", "")) / key2.replaceAll("[^ ]", "").length());
31	        long c = req.getContent().readLong();
32	        ChannelBuffer input = ChannelBuffers.buffer(16);
33	        input.writeInt(a);
34	        input.writeInt(b);
35	        input.writeLong(c);
36	        ChannelBuffer output = ChannelBuffers.wrappedBuffer(MessageDigest.getInstance("MD5").digest(input.array()));
37	        res.setContent(output);
38	    } else {
39	    // Old handshake method with no challenge:
40	        res.addHeader(WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
41	        res.addHeader(WEBSOCKET_LOCATION, getWebSocketLocation(req));
42	        String protocol = req.getHeader(WEBSOCKET_PROTOCOL);
43	        if (protocol != null) {
44	            res.addHeader(WEBSOCKET_PROTOCOL, protocol);
45	        }
46	    }
47	
48	    // Upgrade the connection and send the handshake response.
49	    ChannelPipeline p = ctx.getChannel().getPipeline();
50	    p.remove("aggregator");
51	    p.replace("decoder", "wsdecoder", new WebSocketFrameDecoder());
52	    // Write handshake response to the channel
53	    ctx.getChannel().write(res);
54	    // Upgrade encoder to WebSocketFrameEncoder
55	    p.replace("encoder", "wsencoder", new WebSocketFrameEncoder());
56	    // Initialize the game. Assign players to a game and assign them a letter (X or O)
57	    initGame(ctx);
58	    return;
59	}
60	
61	// Send an error page otherwise.
62	sendHttpResponse(ctx, req, new DefaultHttpResponse(
63	    HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN));
64}

The code above is performed when the client initially connects to the tic-tac-toe server. The WebSocket specification defines how a handshake needs to be performed. There are two versions of the handshake implemented above: one based on the old WebSocket specification (75), and the other based on the new version of the WebSocket specification (76). The biggest difference between the two handshake methods is the old version does not require a challenge while the new version does. To slightly complicate matters, different browsers implement different versions of the WebSocket specification. Another twist is that neither 75 or 76 is the latest version of the WebSocket specification, but these are the most commonly implemented by modern browsers. A deep dive into the WebSocket specification is beyond the scope of this article, but you can find the latest draft specification here. You can find more resources to learn about sockets here.

This brings up an important point; the WebSocket specification is constantly evolving. Fast. I would strongly recommend exploring the option of using a higher-level framework for business programming rather than rolling your own server, because as you see above, you’ll need to keep up-to-date with the latest changes in the spec and which versions are supported by which browsers. It’s generally a good idea to leave this up to framework developers. That being said, even if you’re planning to use a high-level framework, getting an in-depth knowledge of Netty is a very good thing. Down the road if you need the kind of flexibility and power that Twitter does you’ll already know how to implement it.

Also note that we’re programmatically changing the aggregator, encoder, and decoder for this channel only. As soon as the handshake is successful we will be communicating with the client exclusively using the WebSocket protocol rather than HTTP. If we were to leave the original HTTP encoder, decoder, and aggregator alone, our server would not understand how to deal with a WebSocket packet; it would still be trying to piece together usable HTTP requests and responses.

Now let’s take a look at some tic-tac-toe specific logic. First we’ll need to create a game and assign players to it. As players connect to our server they’re paired off and assigned to a game. Our server will be able to support an infinite number of games simultaneously, although I doubt tic-tac-toe will ever become as popular as Twitter.

 1private void initGame(ChannelHandlerContext ctx) {
 2	// Try to find a game waiting for a player. If one doesn't exist, create a new one.
 3	Game game = findGame();
 4	// Create a new instance of player and assign their channel for WebSocket communications.
 5	Player player = new Player(ctx.getChannel());
 6	// Add the player to the game.
 7	Game.PlayerLetter letter = game.addPlayer(player);
 8	// Add the game to the collection of games.
 9	games.put(game.getId(), game);
10	// Send confirmation message to player with game ID and their assigned letter (X or O)
11	ctx.getChannel().write(new DefaultWebSocketFrame(new HandshakeMessageBean(game.getId(), letter.toString()).toJson()));
12	// If the game has begun we need to inform the players. Send them a "turn" message (either "waiting" or "your_turn")
13	if (game.getStatus() == Game.Status.IN_PROGRESS) {
14	    game.getPlayer(PlayerLetter.X).getChannel().write(new DefaultWebSocketFrame(new TurnMessageBean(YOUR_TURN).toJson()));
15	    game.getPlayer(PlayerLetter.O).getChannel().write(new DefaultWebSocketFrame(new TurnMessageBean(WAITING).toJson()));
16	}
17}
18
19private Game findGame() {
20	// Find an existing game and return it
21	for (Game g : games.values()) {
22	    if (g.getStatus().equals(Game.Status.WAITING)) {
23	        return g;
24	    }
25	}
26	// Or return a new game
27	return new Game();
28}

The code above is mainly responsible for creating and maintaining games, which are stored in the TicTacToeServerHandler as a static collection (shared across all instances of our handler). As players connect to our server we assign them to a game and let them know that they are either waiting for an opponent or that an opponent has connected and their game has begun. Exciting!

Finally, we need to accept incoming WebSocket messages. Each message represents a player’s turn (which cell they selected). After we process the turn information we need to push data out to their opponent to let them know how badly they’re getting pwned. We also need to check the status of the ongoing game; it’s fairly important to be able to tell if a game has been won or tied after the last move!

 1private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
 2	Gson gson = new Gson();
 3	IncomingMessageBean message = gson.fromJson(frame.getTextData(), IncomingMessageBean.class);
 4	Game game = games.get(message.getGameId());
 5	Player opponent = game.getOpponent(message.getPlayer());
 6	Player player = game.getPlayer(PlayerLetter.valueOf(message.getPlayer()));
 7	// Mark the cell the player selected.
 8	game.markCell(message.getGridIdAsInt(), player.getLetter());
 9	// Get the status for the current game.
10	boolean winner = game.isPlayerWinner(player.getLetter());
11	boolean tied = game.isTied();
12	// Respond to the opponent in order to update their screen.
13	String responseToOpponent = new OutgoingMessageBean(player.getLetter().toString(), message.getGridId(), winner, tied).toJson();
14	opponent.getChannel().write(new DefaultWebSocketFrame(responseToOpponent));
15	// Respond to the player to let them know they won.
16	if (winner) {
17	    player.getChannel().write(new DefaultWebSocketFrame(new GameOverMessageBean(YOU_WIN).toJson()));
18	} else if (tied) {
19	    player.getChannel().write(new DefaultWebSocketFrame(new GameOverMessageBean(TIED).toJson()));
20	}
21}

Remember earlier that handleWebSocketFrame is one of our own methods, not a callback method provided by Netty. This method is invoked when we inspect the incoming message and determine it’s a WebSocketFrame rather than an HttpRequest. The core of the logic above deals with updating the game board and marking the current player’s last move. We also need to check for victory or draw conditions and update the player and opponent with the latest game status.

That’s it! We’ve coded an entire tic-tac-toe server from scratch and it was very painless. Netty rocks. The only classes we didn’t review are the specific POJOs for tic-tac-toe related logic. You can check out the source below:

Creating the tic-tac-toe client using jQuery

Building our tic-tac-toe server was fairly simple. Building our tic-tac-toe client is even easier thanks to the power of jQuery. If you’d like to skip straight to the source code, it can be viewed below:

https://github.com/rocketpages/TicTacToe-Client

The bulk of the logic is contained in our JavaScript file. After the initial handshake is performed, all communication with the server will be done asynchronously via the WebSocket API. Please note that not all browsers support the WebSocket protocol. This is an up-to-date list of which layout engines support which HTML5 features.

Below is a copy of the JavaScript for the tic-tac-toe client.

  1// Constants - Status Updates
  2var STRATEGIZING_STATUS = "Your opponent is strategizing.";
  3var WAITING_STATUS = "Waiting for an opponent.";
  4var YOUR_TURN_STATUS = "It's your turn!";
  5var YOU_WIN_STATUS = "You win!";
  6var TIED_STATUS = "The game is tied.";
  7var WEBSOCKET_CLOSED_STATUS = "The WebSocket Connection Has Been Closed.";
  8// Constants - Game
  9var PLAYER_O = "O";
 10var PLAYER_X = "X";
 11// Constants - Incoming message types
 12var MESSAGE_HANDSHAKE = "handshake";
 13var MESSAGE_OPPONENT_UPDATE = "response";
 14var MESSAGE_TURN_INDICATOR = "turn";
 15var MESSAGE_GAME_OVER = "game_over";
 16// Constants - Message turn indicator types
 17var MESSAGE_TURN_INDICATOR_YOUR_TURN = "YOUR_TURN";
 18var MESSAGE_TURN_INDICATOR_WAITING = "WAITING";
 19// Constants - Game over message types
 20var MESSAGE_GAME_OVER_YOU_WIN = "YOU_WIN";
 21var MESSAGE_GAME_OVER_TIED = "TIED";
 22// Constants - WebSocket URL
 23var WEBSOCKET_URL = "ws://localhost:9000/websocket";
 24// Variables
 25var player;
 26var opponent;
 27var gameId;
 28var yourTurn = false;
 29// WebSocket connection
 30var ws;
 31$(document).ready(function() {
 32	/* Bind to the click of all divs (tic tac toe cells) on the page
 33	We would want to qualify this if we styled the game fancier! */
 34	$("div").click(function () {
 35	    // Only process clicks if it's your turn.
 36	    if (yourTurn == true) {
 37	        // Stop processing clicks and invoke sendMessage().
 38	        yourTurn = false;
 39	        sendMessage(this.id);
 40	        // Add the X or O to the game board and update status.
 41	        $("#" + this.id).addClass(player);
 42	        $("#" + this.id).html(player);
 43	        $('#status').text(STRATEGIZING_STATUS);
 44	    }
 45	});
 46	// On the intial page load we perform the handshake with the server.
 47	ws = new WebSocket(WEBSOCKET_URL);
 48	ws.onopen = function(event) {
 49	    $('#status').text(WAITING_STATUS);
 50	}
 51	// Process turn message ("push") from the server.
 52	ws.onmessage = function(event) {
 53	    var message = jQuery.parseJSON(event.data);
 54	    // Process the handshake response when the page is opened
 55	    if (message.type === MESSAGE_HANDSHAKE) {
 56	        gameId = message.gameId;
 57	        player = message.player;
 58	        if (player === PLAYER_X) {
 59	            opponent = PLAYER_O;
 60	        } else {
 61	            opponent = PLAYER_X;
 62	        }
 63	    }
 64	    // Process your opponent's turn data.
 65	    if (message.type === MESSAGE_OPPONENT_UPDATE) {
 66	        // Show their turn info on the game board.
 67	        $("#" + message.gridId).addClass(message.opponent);
 68	        $("#" + message.gridId).html(message.opponent);
 69	        // Switch to your turn.
 70	        if (message.winner == true) {
 71	            $('#status').text(message.opponent + " is the winner!");
 72	        } else if (message.tied == true) {
 73	            $('#status').text(TIED_STATUS);
 74	        } else {
 75	            yourTurn = true;
 76	            $('#status').text(YOUR_TURN_STATUS);
 77	        }
 78	    }
 79	    /* The initial turn indicator from the server. Determines who starts
 80	    the game first. Both players wait until the server gives the OK
 81	    to start a game. */
 82	    if (message.type === MESSAGE_TURN_INDICATOR) {
 83	        if (message.turn === MESSAGE_TURN_INDICATOR_YOUR_TURN) {
 84	            yourTurn = true;
 85	            $('#status').text(YOUR_TURN_STATUS);
 86	        } else if (message.turn === MESSAGE_TURN_INDICATOR_WAITING) {
 87	            $('#status').text(STRATEGIZING_STATUS);
 88	        }
 89	    }
 90	    /* The server has determined you are the winner and sent you this message. */
 91	    if (message.type === MESSAGE_GAME_OVER) {
 92	        if (message.result === MESSAGE_GAME_OVER_YOU_WIN) {
 93	            $('#status').text(YOU_WIN_STATUS);
 94	        }
 95	        else if (message.result === MESSAGE_GAME_OVER_TIED) {
 96	            $('#status').text(TIED_STATUS);
 97	        }
 98	    }
 99	}
100	ws.onclose = function(event) {
101	    $('#status').text(WEBSOCKET_CLOSED_STATUS);
102	}
103});
104// Send your turn information to the server.
105function sendMessage(id) {
106	var message = {gameId: gameId, player: player, gridId:id};
107	var encoded = $.toJSON(message);
108	ws.send(encoded);
109}

The bulk of the logic above deals with two distinct activities; maintaining state and processing messages. You’ll notice that when the page first loads we’ll use the documentReady function to initiate the WS handshake. You’ll also notice that we use jQuery to bind different WebSocket events to code blocks.

jQuery makes it fairly trivial to communicate with a WS server. Rather than polling the server, the WebSocket API allows us to bind logic to the onmessage event and perform the appropriate logic. This is awesome! Our tic-tac-toe game is a simple webpage that never needs refreshing. We also don’t need to waist IO constantly polling the server. As soon as our opponent makes his or her move, our screen is immediately updated and we get to take our turn.

Conclusion

That’s a very high level look at the power of Java, Netty, the WebSocket API, and jQuery. We can make a number of improvements to this game, such as tracking and displaying ongoing stats (win, loss, draw) and even allowing the same player to compete in multiple games of tic-tac-toe at once!

Using these technologies we may actually be able to make tic-tac-toe a challenge.

This work by Kevin Webber is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.