Click here to Skip to main content
15,896,912 members
Articles / Programming Languages / C#

Send and receive messages in a LAN with broadcasting

Rate me:
Please Sign up or sign in to vote.
5.00/5 (17 votes)
6 Mar 2012MIT9 min read 95.5K   11.7K   73  
Lightweight .Net library for UDP LAN broadcasting.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Orekaria.Lib.P2P
{
    internal class UdpHelper
    {
        private readonly UdpClient _udpClient;
        private Queue<string> _received;
        private IPEndPoint _remoteEP;

        public UdpHelper(UdpClient udpClient, IPEndPoint remoteEP) {
            _udpClient = udpClient;
            _remoteEP = remoteEP;
        }

        /// <summary>
        ///   Change to your preferred enconding
        /// </summary>
        private static Encoding ChosenEncoder {
            get { return Encoding.UTF8; }
        }

        public Queue<string> Received {
            get {
                if (_received == null) {
                    _received = new Queue<string>();
                    _udpClient.BeginReceive(ReceiveCallback, null);
                }
                return _received;
            }
        }

        ~UdpHelper() {
            _udpClient.Close();
            Debug.Print("Resources freed");
        }

        public void Send(String s) {
            var packetBytes = ChosenEncoder.GetBytes(s);
            _udpClient.Send(packetBytes, packetBytes.Length, _remoteEP);
            // _udpClient.BeginSend(packetBytes, packetBytes.Length, _remoteEP,null,null); // could receive broken packets
            Debug.Print(string.Format("Message sent from {0} on port {1}", _remoteEP.Address, _remoteEP.Port));
        }

        private void ReceiveCallback(IAsyncResult ar) {
            var receiveBytes = _udpClient.EndReceive(ar, ref _remoteEP);
            Debug.Print(string.Format("Message received from {0} on port {1}", _remoteEP.Address, _remoteEP.Port));
            _received.Enqueue(ChosenEncoder.GetString(receiveBytes));
            _udpClient.BeginReceive(ReceiveCallback, 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, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior)
Spain Spain
Hi, I am a Senior Generalist SDE and I have 25+ years of software development experience. My eyes, hands and brain have traveled from Spectrum Basic/assembler all the way to C++, Java and C#. In recent years I have been gluing electronics and software.

I have some Microsoft certifications along with others that I have forgotten.

http://orekaria.com

Comments and Discussions