Creating a Network Framework

In this section, we are going to look at how to create a TCP network framework, which will be fully synchronized with the main game loop on the client side and handle multiple clients simultaneously on the server side. The problem with network code is that when you are listening for messages coming in from, say, a server, you call a read method that will block (wait) for a message to come in, so there is no possible way we could have this in our main loop. Hence, we need to create a separate thread to handle the listening of messages. Because the messages are going to be read in on a separate thread, they will not be synchronized with our main game loop (i.e., they could come in at any point, which is the same problem that we had in Chapter 10 with mouse and keyboard events).

So, what is the solution to this? It is exactly the same solution that we had for the mouse and keyboard events—use the event processor that we created earlier to handle the network events. But wait—we don't actually have any network events as such; all we have is an input stream from the socket, which will block until it reads a message on the separate thread.

If you remember back again to the event processor in Chapter 10, it handles a list of AWTEvent objects, as AWTEvent is the class that all other events, such as MouseEvents and KeyEvents, are derived. Therefore, what we can do is create our own NetworkEvent class, which will extend the AWTEvent class, just as the MouseEvent class extends the AWTEvent class. Then we can use it with the event processor that we created earlier.

Rather than explain all the theory, it's best if we look at a full example of the framework and then at the individual parts that make it all work. So, let's look at the "I'm a circle!" sample network game.



Java 1.4 Game Programming
Java 1.4 Game Programming (Wordware Game and Graphics Library)
ISBN: 1556229631
EAN: 2147483647
Year: 2003
Pages: 237

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net