Click here to Skip to main content
15,884,298 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.2K   11.7K   73  
Lightweight .Net library for UDP LAN broadcasting.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Orekaria.Lib.P2P.Properties;

namespace Orekaria.Lib.P2P
{
    internal class UDPHelper : IDisposable
    {
        private readonly UdpClient _udpClient;
        private IPEndPoint _remoteEP;

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

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

        #region IDisposable Members

        public void Dispose()
        {
            _udpClient.Close();
        }

        #endregion

        public void Send(String s)
        {
            SendData(Encoding.ASCII.GetBytes(s));
        }

        public string Receive()
        {
            var receiveBytes = ReceivedData();
            return UnifiedEnconding.GetString(receiveBytes, 0, receiveBytes.Length);
        }


        private void SendData(byte[] packetBytes)
        {
            _udpClient.Send(packetBytes, packetBytes.Length, _remoteEP);
        }

        private byte[] ReceivedData()
        {
            try {
                var receivedData = _udpClient.Receive(ref _remoteEP);
                return receivedData;
            }
            catch (SocketException ex) {
                return UnifiedEnconding.GetBytes(Resources.TimeOut);
            }
        }
    }
}

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