Click here to Skip to main content
15,893,814 members
Articles / Programming Languages / C#

Topic-based Publish/Subscribe design pattern implementation in C# - Part I (Using socket programming)

Rate me:
Please Sign up or sign in to vote.
4.94/5 (28 votes)
23 Mar 2009CPOL16 min read 133K   3.2K   81  
Implementation of a topic based Publish Subscribe design pattern using socket programming, and a proprietary messaging protocol.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Configuration;

namespace SocketSubscriber
{
    public partial class Subscriber : Form
    {
        Socket _client;
        EndPoint _remoteEndPoint;
        byte[] _data;
        int _recv;
        Boolean _isReceivingStarted = false;

        public Subscriber()
        {
            InitializeComponent();

            string serverIP = ConfigurationSettings.AppSettings["ServerIP"];
            IPAddress serverIPAddress = IPAddress.Parse(serverIP);
            int serverPort = Convert.ToInt32(ConfigurationSettings.AppSettings["ServerPort"]);

            _client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _remoteEndPoint = new IPEndPoint(serverIPAddress, serverPort);


            txtTopicName.Text = "Bangladesh";

        }


        void ReceiveDataFromServer()
        {
            EndPoint publisherEndPoint = _client.LocalEndPoint;
            while (true)
            {
                _recv = _client.ReceiveFrom(_data, ref publisherEndPoint);
                string msg = Encoding.ASCII.GetString(_data, 0, _recv) + "," + publisherEndPoint.ToString();
                lstEvents.Invoke(new AddToTextBoxDelegate(AddToTextBox), msg);
            }
        }

        public delegate void AddToTextBoxDelegate(string message);
        public void AddToTextBox(string message)
        {
            string[] messageParts = message.Split(",".ToCharArray());
            int itemNum = (lstEvents.Items.Count < 1) ? 0 : lstEvents.Items.Count;
            lstEvents.Items.Add(itemNum.ToString());
            lstEvents.Items[itemNum].SubItems.AddRange(new string[] { messageParts[0], messageParts[1], messageParts[2] });
        }

        private void btnClearAstaListView_Click(object sender, EventArgs e)
        {
            lstEvents.Items.Clear();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string topicName = txtTopicName.Text.Trim();
                if (string.IsNullOrEmpty(topicName))
                {
                    MessageBox.Show("Please Enter a Topic Name");
                    return;
                }
                string command = "UnSubscribe";

                string message = command + "," + topicName;
                _client.SendTo(Encoding.ASCII.GetBytes(message), _remoteEndPoint);
                ((Button)sender).Visible = false;
                button3.Visible = true;
            }
            catch
            {

            }

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string topicName = txtTopicName.Text.Trim();
            if (string.IsNullOrEmpty(topicName))
            {
                MessageBox.Show("Please Enter a Topic Name");
                return;
            }
            ((Button)sender).Visible = false;
            button2.Visible = true;

            string Command = "Subscribe";

            string message = Command + "," + topicName;
            _client.SendTo(Encoding.ASCII.GetBytes(message), _remoteEndPoint);

            if (_isReceivingStarted == false)
            {
                _isReceivingStarted = true;
                _data = new byte[1024];
                Thread thread1 = new Thread(new ThreadStart(ReceiveDataFromServer));
                thread1.IsBackground = true;
                thread1.Start();
            }
        }
    }
}

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 Code Project Open License (CPOL)


Written By
Software Developer (Senior) CP
Australia Australia
I am an Independent Contractor in Brisbane, Australia. For me, programming is a passion first, a hobby second, and a career third.

My Blog: http://weblogs.asp.net/razan/






Comments and Discussions