Quantcast
Channel: Programming – Xinyustudio
Viewing all articles
Browse latest Browse all 284

Using RabbitMQ in C# (II) Sending message to RabbitMQ

$
0
0

Create a Winform application, add below UI to the form:

image

Add RabbitMQ .net client library in Visual Studio by using Nuget: to install RabbitMQ.Client, run the following command in the Package Manager Console

PM> Install-Package RabbitMQ.Client

Add below code in Form.Load() function

private void Form1_Load(object sender, EventArgs e)
{
            UserNameTextBox.Text = “guest”;
            PasswordTextBox.Text = “guest”;
            HostTextBox.Text = “localhost”;
            PortTextBox.Text = “5672”;

            //This works
            //factory.UserName = UserNameTextBox.Text;
            //factory.Password = PasswordTextBox.Text;
            //factory.VirtualHost = “/”;
            //factory.HostName = HostTextBox.Text;

            factory.Uri = string.Format(“amqp://{0}:{1}@{2}:{3}{4}”,
                UserNameTextBox.Text, PasswordTextBox.Text,
                HostTextBox.Text, PortTextBox.Text, “/”);

            conn = factory.CreateConnection();
            if (conn == null)
                LogListBox.Items.Add(“Connection Fails”);
            else
                LogListBox.Items.Add(“Connection Success”);

            PubChannel = conn.CreateModel();
            LogListBox.Items.Add(PubChannel == null ? “pub channel creation fails” :
                                                      “pub channel creation success”);
}

Add event handler for the button “Send”:

var msg = MessageTextBox.Text;
if (string.IsNullOrEmpty(msg))
       return;
byte[] messageBodyBytes = Encoding.UTF8.GetBytes(msg);
PubChannel.BasicPublish(exchangeName, routingKey, null, messageBodyBytes);
LogListBox.Items.Add("Sending Message: " + msg);

If you follow the previous post, the variables are set as follows:

string exchangeName = "Demo";
string queueName ="example", routingKey = "example";       

Run the application, and click the Send button, go to web admin page, you will see your messages are sent there!

image image


Viewing all articles
Browse latest Browse all 284

Trending Articles