27
|
1 using System;
|
|
2 using System.Diagnostics;
|
|
3 using System.Text;
|
|
4 using Common.Messages;
|
|
5 using GalaSoft.MvvmLight.Messaging;
|
|
6 using RabbitMQ.Client;
|
|
7 using RabbitMQ.Client.Events;
|
|
8 using RabbitMQ.Client.MessagePatterns;
|
|
9
|
|
10 namespace Server.Listeners
|
|
11 {
|
|
12 class RabbitQueueListener : IListener
|
|
13 {
|
|
14 public bool IsListening { get; set; }
|
|
15 private readonly int _port;
|
28
|
16 private Subscription _subscription;
|
|
17 private string _queueName;
|
27
|
18
|
28
|
19 public RabbitQueueListener(int port, string queueName)
|
27
|
20 {
|
|
21 _port = port;
|
28
|
22 _queueName = queueName;
|
27
|
23 }
|
|
24
|
|
25 public void Start()
|
|
26 {
|
|
27 try
|
|
28 {
|
28
|
29 if (IsListening) return;
|
|
30
|
27
|
31 var serverAddress = "localhost:" + _port;
|
|
32
|
|
33 var connectionFactory = new ConnectionFactory { Address = serverAddress };
|
|
34
|
|
35 using (var connection = connectionFactory.CreateConnection())
|
|
36 {
|
|
37 using (var channel = connection.CreateModel())
|
|
38 {
|
31
|
39 Log("Opening listener");
|
28
|
40 string queueName = channel.QueueDeclare(_queueName, false, false, false, null);
|
27
|
41 channel.QueueBind(queueName, "amq.direct", queueName, null);
|
|
42
|
28
|
43 using (_subscription = new Subscription(channel, queueName))
|
27
|
44 {
|
|
45 IsListening = true;
|
|
46 while (IsListening)
|
|
47 {
|
28
|
48 foreach (BasicDeliverEventArgs eventArgs in _subscription)
|
27
|
49 {
|
28
|
50 //Log(Encoding.UTF8.GetString(eventArgs.Body));
|
|
51 Messenger.Default.Send(new RabbitClientMessage());
|
|
52 _subscription.Ack();
|
27
|
53 }
|
|
54 }
|
|
55 }
|
|
56 }
|
|
57 }
|
|
58 }
|
|
59 catch (Exception e)
|
|
60 {
|
|
61 Log(e.Message);
|
|
62 }
|
|
63 }
|
|
64
|
|
65 public void Stop()
|
|
66 {
|
31
|
67 if (!IsListening) return;
|
28
|
68 _subscription.Close();
|
27
|
69 IsListening = false;
|
31
|
70 Log("Listener closed.");
|
27
|
71 }
|
|
72
|
|
73 private void Log(string message)
|
|
74 {
|
|
75 Debug.WriteLine(message);
|
|
76 Messenger.Default.Send(new RabbitLogMessage() { Body = message });
|
|
77 }
|
|
78 }
|
|
79 }
|