Free cookie consent management tool by TermsFeed Policy Generator

source: branches/thasling/DistributedGA/DistributedGA.Core/Implementation/WcfMessageService.cs @ 13547

Last change on this file since 13547 was 13547, checked in by thasling, 9 years ago

Added Dispose() to MessageHandler and WCF service host

File size: 1.9 KB
Line 
1using System;
2using System.Net;
3using System.Net.Sockets;
4using System.ServiceModel;
5using System.Threading;
6using DistributedGA.Core.Domain;
7using DistributedGA.Core.Interface;
8
9namespace DistributedGA.Core.Implementation {
10  public class WcfMessageService : IMessageService {
11    public event EventHandler<MessageRecieveEventArgs> OnPopulationRecieved;
12
13    private static ManualResetEvent _ResetEvent = new ManualResetEvent(false);
14
15    private IMessageContract messageContract = null;
16
17    public int Init(string ip) {
18      int port = 0;
19      port = FreeTcpPort();
20
21      messageContract = new MessageContractImpl();
22      messageContract.MessageRecieved += new EventHandler<MessageRecieveEventArgs>(OnMessageRecieved);
23
24      var serviceUrl = "DistributedGA.svc";
25      new Thread(() => {
26        var baseUri = new Uri(string.Concat("http://", ip, ":", port, "/DistributedGA"));
27        var serviceUri = new Uri(baseUri, serviceUrl);
28        BasicHttpBinding binding = new BasicHttpBinding();
29        //using (var host = new ServiceHost(typeof(MessageContractImpl), serviceUri))
30
31        using (var host = new ServiceHost(messageContract, serviceUri)) {
32          host.AddServiceEndpoint(typeof(IMessageContract), binding, serviceUri);
33
34          host.Open();
35
36          _ResetEvent.WaitOne();
37        }
38      }).Start();
39      //close service again:
40      //  _ResetEvent.Set();
41      return port;
42    }
43
44    public void Dispose() {
45      _ResetEvent.Set();
46    }
47
48    private int FreeTcpPort() {
49      TcpListener l = new TcpListener(IPAddress.Loopback, 0);
50      l.Start();
51      int port = ((IPEndPoint)l.LocalEndpoint).Port;
52      l.Stop();
53      return port;
54    }
55
56    private void OnMessageRecieved(object sender, MessageRecieveEventArgs e) {
57      if (OnPopulationRecieved != null) {
58        OnPopulationRecieved(this, e);
59      }
60    }
61  }
62}
Note: See TracBrowser for help on using the repository browser.