Game Development Reference
In-Depth Information
As we are just working with single messages, we don't need to establish a connec-
tion, and instead our server just listens for individual messages. To do this we need
to create a DatagramSocket , as shown:
DatagramSocket^ listenSocket = ref new
DatagramSocket();
listenSocket->MessageReceived += ref new
TypedEventHandler<DatagramSocket^,
DatagramSocketMessageReceivedEventArgs^>(this,
&MyClass::ReceiveMessage);
listenSocket->BindServiceNameAsync("6000");
You can see that this is similar to the StreamSocketListener from the TCP serv-
er. However, in this case the DatagramSocket handles everything. Here we will
create the new socket, and then hook into the MessageReceived event. Once
we've done that we can tell the socket to bind to a particular port and start listening
for messages with the BindServiceNameAsync() method, which takes the name
of the service (or port) just like the TCP.
Inside ReceiveMessage (the handler for MessageReceived ), we are provided
with the listening socket and a DatagramSocketMessageReceivedEventArgs
object as the method arguments. Here we can access the message itself by retriev-
ing the DataReader from the DatagramSocketMessageReceivedEventArgs
using args->GetDataReader() .
To send a message we need the endpoint that we want to connect to, the port, and
the data we want to send. This is shown in the following piece of code:
auto host = ref new HostName("localhost");
auto port = ref new Platform::String(L"6000");
DatagramSocket^ socket = ref new
DatagramSocket();
socket->ConnectAsync(hostName,
ServiceNameForConnect->Text);
Search WWH ::




Custom Search