Example LiteNetLib

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

Using Section

You will need to have the following in the using section of your Game1.cs:

using System;
using System.Timers;
using System.Threading;
using LiteNetLib;
using LiteNetLib.Utils;

Variables

We will need the following variables:

bool server = false;
bool client = false;
NetManager Server;
NetManager Client;
System.Timers.Timer atimer;

The booleans will be used so that only the server or client can be started and not both. The timer will be used to send a message every n seconds.

Controlling Exit

In the Update method you will see the first line of code controls the exit of the game. We need to add the code to stop either the Server or Client if they are currently running:

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
            {
                if (client)
                    Client.Stop();
                else if (server)
                    Server.Stop();
                Exit();
            }

Start the Server

So after the exit code we can check to see if the 'S' key is pressed to start the server. We need to check to see if the client or server have already been started:

if (Keyboard.GetState().IsKeyDown(Keys.S))
            {
                if(!server && !client)
                {
                    server = true;
                    EventBasedNetListener listener = new EventBasedNetListener();
                    Server = new NetManager(listener);
                    Server.Start(9050 /* port */);

                    listener.ConnectionRequestEvent += request =>
                    {
                        if (Server.PeersCount < 10 /* max connections */)
                            request.AcceptIfKey("SomeConnectionKey");
                        else
                            request.Reject();
                    };

                    listener.PeerConnectedEvent += peer =>
                    {
                        Console.WriteLine("We got connection: {0}", peer.EndPoint); // Show peer ip
                        NetDataWriter writer = new NetDataWriter();                 // Create writer class
                        writer.Put("Hello client!");                                // Put some string
                        peer.Send(writer, DeliveryMethod.ReliableOrdered);             // Send with reliability
                    };

                    listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) =>
                    {
                        Console.WriteLine("We got: {0}", dataReader.GetString(100 /* max length of string */));
                        dataReader.Recycle();
                    };
                }
            }

The above codes the listener to handle Connections, and when a client connects it uses the PeerConnectedEvent to send a message back to the client. The final listener is for the server to listen out for messages from the client after connection. At the moment every message will be displayed using Console.Writeline, but you can do more than just 'GetString()'. For example you can also get many other data types, you can also use 'TryGetString' (and for the other data types), and you can also use 'PeekString' to get the next string without actually reading it and moving on to the next value in the reader.

Start the Client

So after the server code we can check to see if the 'C' key is pressed to start the client. We need to check to see if the client or server have already been started:

            if (Keyboard.GetState().IsKeyDown(Keys.C))
            {
                if (!server && !client)
                {
                    client = true;
                    EventBasedNetListener listener = new EventBasedNetListener();
                    Client = new NetManager(listener);

                    Client.Start();
                    Client.Connect("localhost" /* host ip or name */, 9050 /* port */, "SomeConnectionKey" /* text key or NetDataWriter */);

                    listener.NetworkReceiveEvent += (fromPeer, dataReader, deliveryMethod) =>
                    {
                        Console.WriteLine("We got: {0}", dataReader.GetString(100 /* max length of string */));
                        dataReader.Recycle();
                    };
                }
            }

The code above handles the connection, and also to make the listener listen for network messages.

Set the timer / Sending messages

This timer is purely used to send a message every n seconds, in your game a player action could send a message instead. In the LoadContent method add the following to set up a timer:

            atimer = new System.Timers.Timer();
            atimer.Enabled = false;
            atimer.Interval = 4000;
            atimer.Elapsed += Atimer_Elapsed;

Now create the following method:

        private void Atimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            atimer.Enabled = false;
            count++;
            NetDataWriter writer = new NetDataWriter();                 // Create writer class
            writer.Put("Message: "+count);                                // Put some string

            if(client)
                Client.SendToAll(writer, DeliveryMethod.ReliableOrdered);
            else if(server)
                Server.SendToAll(writer, DeliveryMethod.ReliableOrdered);
        }

This is just an example to send a stream of messages, but the key is to use a NetDataWriter and 'SendToAll' to send a message whenever you need to.

Set the Client or Server to listen

Finally in the update method, after the code to start the client or server, we need to add the following code:

            if(server)
            {
                Server.PollEvents();
                Thread.Sleep(15);
                if (!atimer.Enabled)
                    atimer.Enabled = true;
            }
            else if (client)
            {
                Client.PollEvents();
                Thread.Sleep(15);
                if (!atimer.Enabled)
                    atimer.Enabled = true;
            }

If the client or server was started, the PollEvents to receive any messages. Each will also check the timer, and if it is not enabled it will enable the timer. The timer in this example is just to send a message every n seconds.

Running it

So now you should be able to run the game. Also run a second copy by navigating to the project folder, bin, windows, x86, debug then run the '.exe' file.

On one window press 'S' to start the server, and on the other press 'C' to start the client. You should see a message to show they are connected, and then every so often a message will be sent which includes a number.