Game Development Reference
In-Depth Information
These benefits come with a downside, though. There is an overhead associated with
resending and reordering packets, which in the fast-paced game world can lead to
issues in keeping two players in sync. If you aren't sending a lot of data then this isn't
a big deal, and if your game doesn't require a new world state all the time then you
could use this without worrying too much. If, however, you are writing a fast-paced
game such as a first-person shooter that requires a constant stream of updates, you
might want to consider using UDP instead.
To make use of this socket, you can either establish the connection yourself, or if
you are using the
PeerFinder
class, the
ConnectAsync()
method will give you a
connected
StreamSocket
that you can use in your game. Let's quickly take a look
at how to create a
StreamSocket
manually.
There are two parts to a TCP connection:
listener
and
socket
. You should use the
listener to wait and listen for an incoming connection, and then respond to that con-
nection using a
StreamSocket
. This is defined in the following piece of code:
StreamSocketListener^ listener = ref new
StreamSocketListener();
listener->ConnectionReceived += ref new
TypedEventHandler<StreamSocketListener^,
StreamSocketListenerConnectionReceivedEventArgs^>(this,
&MyClass::HandleConnection);
listener->BindServiceNameAsync("6000");
For the server, we will start by creating a
StreamSocketListener
. This handles
waiting for a connection and, if one occurs, the
ConnectionReceived
event is
raised, which we hooked into earlier.
Once we have hooked into the
ConnectionReceived
event we can tell the listener
to start listening, which we do using the
BindServiceNameAsync()
method. This
method takes a string which in most cases will just specify a port number to listen
on as shown earlier. Remember that this is the WinRT
Platform::String
rather
than the standard library string, so ensure you're providing the correct one.
When a connection arrives, our handler will be called and we will be provided with
a
StreamSocketListenerConnectionReceivedEventArgs
object. Inside this