RabbitMQ, Python and C#

17 Apr
C# consuming a message from python producer via RabbitMQ.

C# consuming a message from python producer via RabbitMQ.

I don’t know much about software patterns. My applications tend to be more of the script variety – though I throw some OOP in for fun. I recently came across RabbitMQ – a message broker. It sits between producers and consumers of messages – it is the queue. I tested out the python hello world example and then got the bright idea to use C# as one piece. The thing about RabbitMQ is that it uses a standard Advanced Messaging Queuing Protocol. This means any language or application that implements that protocol can communicate – think HTTP or FTP protocols.

Here is the python producer taken from the RabbitMQ Tutorial. You will need pika.

import pika
import logging
connection = pika.BlockingConnection(pika.ConnectionParameters(host=’localhost’))
channel = connection.channel()


channel.basic_publish(exchange=”,routing_key=’hello’,body=’Hello World!’)
print ” [x] Sent ‘Hello World!'”


Simple enough. Now I wrote a C# form that consumes the messages onClick of a button and displays them in a text box – appending the new messages as they come in.

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 RabbitMQ.Client;


namespace WindowsFormsApplication1
public partial class Form1 : Form
public Form1()

private void button1_Click(object sender, EventArgs e)
var connectionFactory = new ConnectionFactory();
IConnection connection = connectionFactory.CreateConnection();
IModel channel = connection.CreateModel();
channel.QueueDeclare(“hello”, false, false, false, null);
BasicGetResult result = channel.BasicGet(“hello”, true);
if (result != null)
string message = Encoding.UTF8.GetString(result.Body);

textBox1.Text += message+”\r\n”;




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: