using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { string hostName = "192.168.1.61"; string userName = "test"; string passWord = "123456"; //信息是否持久化 bool durable = false; public Form1() { InitializeComponent(); //防止多线程报错 System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; textBox2.ReadOnly = true; textBox2.ScrollBars = ScrollBars.Vertical; var thrd = new Thread(GetMessage); thrd.IsBackground = true; thrd.Name = "DownLoad"; thrd.Start(); } private void button1_Click(object sender, EventArgs e) { var factory = new ConnectionFactory(); factory.HostName = hostName; factory.UserName = userName; factory.Password = passWord; //创建一个连接 using (var connection = factory.CreateConnection()) { //创建一个通道 using (var channel = connection.CreateModel()) { //创建一个队列 channel.QueueDeclare("hello", durable, false, false, null); //信息持久化 var properties = channel.CreateBasicProperties(); properties.Persistent = true; string message = textBox1.Text; var body = Encoding.UTF8.GetBytes(message); //发送数据 channel.BasicPublish(exchange: "", routingKey: "hello", basicProperties: null, body: body); } } } private void button2_Click(object sender, EventArgs e) { } private void GetMessage() { var factory = new ConnectionFactory(); factory.HostName = hostName; factory.UserName = userName; factory.Password = passWord; //创建一个连接 using (var connection = factory.CreateConnection()) { //创建一个通道 using (var channel = connection.CreateModel()) { //创建一个队列 channel.QueueDeclare("hello", durable, false, false, null); channel.BasicQos(0, 1, false); var consumer = new QueueingBasicConsumer(channel); channel.BasicConsume("hello", true, consumer); while (true) { //接收信息 var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue(); var body = ea.Body; var message = Encoding.UTF8.GetString(body); textBox2.Text += message + " "; } } } } } }