Warm tip: This article is reproduced from serverfault.com, please click

RabbitMQ

发布于 2020-11-30 07:35:18

I tried to send a custom message for pub/sub using RabbitMQ tutorial but in winform.

I already passed the text from textbox to the encoder. However, it gave me a NullReference at basicPublish.

Here's the code

using System;
using System.Text;
using System.Windows.Forms;
using RabbitMQ.Client;

namespace Publisher
{
    public partial class Form1 : Form
    {
        public string exName;
        public IModel channel;
        public IConnection conn;

        public Form1()
        {
            InitializeComponent();
            ConnectionFactory factory = new ConnectionFactory();
            factory.UserName = "guest";
            factory.Password = "guest";
            factory.VirtualHost = "/";
            factory.HostName = "localhost";

            IConnection conn = factory.CreateConnection();
            IModel channel = conn.CreateModel();
            channel.ExchangeDeclare("logs", ExchangeType.Fanout);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            channel.Close();
            conn.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string pesan = richTextBox1.Text;
            textBox1.Text = pesan;
            var body = Encoding.UTF8.GetBytes(pesan);
            channel.BasicPublish(exchange: "logs",
                                 routingKey: "",
                                 basicProperties: null,
                                 body: body);
        }
    }
}

Is there anything that I should do before basicPublish?

Questioner
Adhityo Putro
Viewed
0
vernou 2020-11-30 16:10:09

In the constructor :

public Form1()
{
    ...
    //Declare new variable conn
    IConnection conn = factory.CreateConnection();
    //Declare new variable channel
    IModel channel = conn.CreateModel();
    //The fields this.channel and this.conn are never initialized
    //and their value is null
}

Remove the type before initialize the value in field :

public Form1()
{
    ...
    conn = factory.CreateConnection();
    channel = conn.CreateModel();
    channel.ExchangeDeclare("logs", ExchangeType.Fanout);
}