.net中使用消息传递数据
使用消息传递数据时,一般情况下数据量较少。在我所使用的项目中,使用它最大的好处就是不用考虑对方是否是运行状态,只要对方上线,它就可能收到。在项目中,它的作用是在产生较大的数据时,先用消息进行通知,在对方收到消息后,再从Web服务来收取,代码如下,有改动:
发送端:
1 messageModel.transfersModel tmodel = new messageModel.transfersModel(sourcetext.Trim(), itype, content.Trim());
2 using (MessageQueue queue = new MessageQueue("FormatName:DIRECT=tcp:" + address.Trim() + @"\Private$\message"))
3 {
4 MessageQueueTransaction transMes = new MessageQueueTransaction();
5 try
6 {
7 transMes.Begin();
8 queue.Send(tmodel, "transferMessage : { " + sourceip.Trim() + " }");
9 transMes.Commit();
10 }
11 catch
12 {
13 transMes.Abort();
14 }
15 }
16
2 using (MessageQueue queue = new MessageQueue("FormatName:DIRECT=tcp:" + address.Trim() + @"\Private$\message"))
3 {
4 MessageQueueTransaction transMes = new MessageQueueTransaction();
5 try
6 {
7 transMes.Begin();
8 queue.Send(tmodel, "transferMessage : { " + sourceip.Trim() + " }");
9 transMes.Commit();
10 }
11 catch
12 {
13 transMes.Abort();
14 }
15 }
16
接收端:
1 private Thread receiveMessageThread;
2
3 private void Form_Load(object sender, EventArgs e)
4 {
5 ///接收消息
6 this.queue = new MessageQueue(@".\Private$\tgatemessage");
7 System.Type[] types = new Type[] { typeof(messageModel.transfersModel) };
8 queue.Formatter = new XmlMessageFormatter(types);
9
10 this.receiveMessageThread = new Thread(new ThreadStart(this.getMessage));
11 this.receiveMessageThread.IsBackground = true;
12 this.receiveMessageThread.Start();
13 }
14
15
16
17 接收消息
45
46
2
3 private void Form_Load(object sender, EventArgs e)
4 {
5 ///接收消息
6 this.queue = new MessageQueue(@".\Private$\tgatemessage");
7 System.Type[] types = new Type[] { typeof(messageModel.transfersModel) };
8 queue.Formatter = new XmlMessageFormatter(types);
9
10 this.receiveMessageThread = new Thread(new ThreadStart(this.getMessage));
11 this.receiveMessageThread.IsBackground = true;
12 this.receiveMessageThread.Start();
13 }
14
15
16
17 接收消息
45
46
接收端使用一个单独的线程来监测消息,而消息的读取本身具有阻塞,所以在没有新消息时此线程处于停止状态,在有新的消息时才运行,运行完成后再次阻塞。发送端与接收端共用了一个数据类,内容可根据自己的需要进行定义。