Free cookie consent management tool by TermsFeed Policy Generator

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

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

Connectionstring to peerlistserver now in app.config

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 = GetRanodmFreePort();
20      port = FreeTcpPort();
21
22      messageContract = new MessageContractImpl();
23      messageContract.MessageRecieved += new EventHandler<MessageRecieveEventArgs>(OnMessageRecieved);
24
25      var serviceUrl = "DistributedGA.svc";
26      new Thread(() => {
27        var baseUri = new Uri(string.Concat("http://", ip, ":", port, "/DistributedGA"));
28        var serviceUri = new Uri(baseUri, serviceUrl);
29        BasicHttpBinding binding = new BasicHttpBinding();
30        //using (var host = new ServiceHost(typeof(MessageContractImpl), serviceUri))
31
32        using (var host = new ServiceHost(messageContract, serviceUri)) {
33          host.AddServiceEndpoint(typeof(IMessageContract), binding, serviceUri);
34
35          host.Open();
36
37          _ResetEvent.WaitOne();
38        }
39      }).Start();
40      //close service again:
41      //  _ResetEvent.Set();
42      return port;
43    }
44
45    private int FreeTcpPort() {
46      TcpListener l = new TcpListener(IPAddress.Loopback, 0);
47      l.Start();
48      int port = ((IPEndPoint)l.LocalEndpoint).Port;
49      l.Stop();
50      return port;
51    }
52
53    private void OnMessageRecieved(object sender, MessageRecieveEventArgs e) {
54      if (OnPopulationRecieved != null) {
55        OnPopulationRecieved(this, e);
56      }
57    }
58
59  }
60}
Note: See TracBrowser for help on using the repository browser.