Skip to content
TheThing edited this page Mar 9, 2011 · 1 revision

The Network Library is mostly event driven. Each packet received and sent contains a packet code. This packet code determines which event should be executed. Property changed packets contain the packet code of -774 where as the packet code for collection changed is -773. If any incoming packets match that code, the corresponding events are executed. When you register events to the Network Library you assign a code to it. Than your event is run every time incoming packets contain that code. Let's look at some examples:

Important note

Before you are able to send and receive anything you have to configure the Network Library how it will execute the events and methods registered in it. There are 2 ways to configure it. One way is to use the Dispatcher in a WPF window and add it to the Network Library. If done, all code inside the methods and events will be run in a relative thread-safe enviroment. If you are using a Dispatcher, you have to let the Network Library know. By default the Network Library will ignore the dispatcher. When the Network Library is set to ignore the Dispatcher, all the methods and events are not thread-safe meaning you have to add locks and such yourself. To add the Dispatcher of a WPF window to the Network Library you do the following:

ourNetworkConnection.Dispatcher = Dispatcher;
ourNetworkConnection.IgnoreDispatcher = false;

If you are developing in other forms such as Console or Windows.Form you have to configure the Network Library to ignore the Dispatcher which is done like this:

ourNetworkConnection.IgnoreDispatcher = true;

This is the default setting and doesn't need to be changed as of version 1.0.0.4.

Registering methods

Continuing from our last example, we add the following line after we initialize our INetwork interface:

int code = 0;
ourNetworkConnection.RegisterEvent(code, eventThatShouldBeRun);

Now that we have registered a method with code 0 we now only have to create the method:

private void eventThatShouldBeRun(object source, NetworkEventArgs args)
{
}

Everytime an incoming packet contains the code of 0, that method will be run. The NetworkEventArgs contains the data, type as well as other information of the packet. The source is the packet in it's raw form. Because we have our method, lets make it print out the contents of the packet:

private void eventThatShouldBeRun(object source, NetworkEventArgs args)
{
	Console.WriteLine("Packet was received with code 0, the contents: {0}", args.Data);
}

This is how you register events into the Network Library.

Sending data

Sending data is a lot more simpler than registering methods. Here is a quick example of how you send the string "Hello World" over the network with code 0:

int code = 0;
connection.SendEvent(code, "Hello World");

Just like that. SendEvent has more parameters if you want to be more specific. You can exclude clients from receiving the packet and you can also make it send the packet to yourself which can be useful in some situations. It also have a method called SendSingleEvent which is used when you want to send a packet only to a single client. We can also send objects and other data as well.

Putting it all together

Now that we know how to register events and send data it's time to put it all together. In this example I create a very basic chat console program. I send custom objects over to demonstrate how such is accomplished.

using System;
using NetworkLibrary.Core;

namespace ConsoleTest
{
	public class MainProgram
	{
		enum PacketCode { SendText = 0 }

		static INetwork theConnection;

		public static void Main(params string[] args)
		{
			Console.Write("Type 'h' to create host or 'c' to create a client\nInput: ");
			if (Console.ReadLine() == "h")
			{
				theConnection = new ConnectionHost(33050);

				try
				{
					(theConnection as ConnectionHost).StartBroadcasting();
					Console.WriteLine("\nHost up and running.");

					StartDefault();
				}
				catch (Exception e)
				{
					Console.WriteLine("\nError while creating host: {0}.", e.Message);
				}
			}
			else
			{
				theConnection = new ConnectionClient();
				try
				{
					(theConnection as ConnectionClient).Connect("127.0.0.1", 33050);
					Console.WriteLine("\nSucessfully connected.");

					StartDefault();
				}
				catch (Exception e)
				{
					Console.WriteLine("\nError while connecting: {0}.", e.Message);
				}
			}
			Console.Write("\n\nPress any key to quit.");
			Console.ReadKey();
		}

		private static void StartDefault()
		{
			//Set the Network Library to ignore the Dispatcher.
			theConnection.IgnoreDispatcher = true;
			//Register our TestClass to the Library. Doing so will allow us to send and receive objects of this kind.
			theConnection.NetworkDataHandler.RegisterType(typeof(TestClass));
			//Register our event.
			theConnection.RegisterEvent((int)PacketCode.SendText, networkTextReceived);

			while (true)
			{
				Console.WriteLine("\nType text to send or 'q' to quit: ");
				string input = Console.ReadLine();
				if (input == "q")
					break;
				else
				{
					TestClass c = new TestClass();
					c.StringArray = input.Split(' ');
					theConnection.SendEvent((int)PacketCode.SendText, c);
				}
			}
		}

		private static void networkTextReceived(object source, NetworkEventArgs args)
		{
			TestClass test = args.Data as TestClass;
			Console.WriteLine("\nReceived text, printing it out:\n\t");
			foreach (string s in test.StringArray)
				Console.Write(s + " ");
		}
	}

	public class TestClass
	{
		public TestClass()
		{
		}

		private string[] _stringArray;

		public string[] StringArray
		{
			get { return _stringArray; }
			set { _stringArray = value; }
		}
	}
}

You might notice the following line in the code:

theConnection.NetworkDataHandler.RegisterType(typeof(TestClass));

Because we will be sending custom objects over the network we need to make sure the type of the object is registered into the Network Library. If the type was not registered, Network Library would have no idea which kind of type it was because Network Library doesn't have direct access to the classes in your application. Therefore, for every type of custom objects we send, we need to register it just like I did above. This however only needs to be done once.

Well, now that is finished, continue on for information on how to handle errors and get debugging information from the Network Library in my next section, Handling Exceptions.

Clone this wiki locally