Click here to Skip to main content
15,887,856 members
Articles / Programming Languages / C#

Scalable Server Events with .NET UDP Sockets

Rate me:
Please Sign up or sign in to vote.
4.70/5 (10 votes)
21 Nov 200610 min read 68.8K   2.3K   59  
An article on notifying WinForms clients on a network that an event which concerns them has transpired.
using System;
using System.Net;
using System.Net.Sockets;
using UDPEvents.AppCommands;

namespace UDPEvents.UDP
{
	/// <summary>
	/// Class to braodcast UDP Commands. Normally you would just use the UDPClient class, but
	/// for our demo app we want to be able to run multiple copies of the apps on the same machine,
	/// and therefore they each need their own UDP port
	/// </summary>
	public class UDPBroadcaster
	{
		private static void SendCommand(AppCommand cmd, int port, string hostName)
		{
			byte[] data = AppCommandTranslator.ToBinary(cmd);
			UdpClient sender = new UdpClient();
			IPAddress endAddress = IPAddress.Broadcast;
			if (hostName != null)
			{
				IPHostEntry host = Dns.GetHostByName(hostName);
				if (host != null && host.AddressList != null && host.AddressList.Length > 0)
					endAddress = host.AddressList[0];
			}
			IPEndPoint end = new IPEndPoint(endAddress, port);
			sender.Send(data, data.Length, end);
		}
			
		
		/// <summary>
		/// Routine to broadcast to one specific machine. Assumes that this machine is the server
		/// and as such only broadcasts on one port
		/// </summary>
		public static void BroadcastCommand(AppCommand cmd, string hostName)
		{
			SendCommand(cmd, UDPPorts.ServerPort(), hostName);
		}

		/// <summary>
		/// Routine to broadcast to the whole network. Broadcasts on the server, manager and all client
		/// ports
		/// </summary>
		public static void BroadcastCommand(AppCommand cmd)
		{
			SendCommand(cmd, UDPPorts.ServerPort(), null);
			SendCommand(cmd, UDPPorts.ManagerPort(), null);
			for(int i = 0; i < Consts.MaxClients; i++)
			{
				SendCommand(cmd, UDPPorts.ClientPort(i), null);	
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
South Africa South Africa
Joon du Randt is a technical team leader for DVT, a software company based in Cape Town, South Africa.

He has been programming since the age of 10, and has been programming as a career since age 19.

Originally a Delphi developer, he made the swtich to C# in 2005 and has not regretted it since

Comments and Discussions