Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 13956 was 13956, checked in by thasling, 8 years ago

#2615:
finally fixed bug concerning message send to the wrong peers
also made communicationRate and messageCacheCapacity as paramters
integration in P2PMigrationAnalyzer still TBD

File size: 1.7 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> OnDataRecieved;
12
13    private 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("net.tcp://", ip, ":", port, "/DistributedGA"));
27        var serviceUri = new Uri(baseUri, serviceUrl);
28        NetTcpBinding binding = new NetTcpBinding();
29
30        using (var host = new ServiceHost(messageContract, serviceUri)) {
31          host.AddServiceEndpoint(typeof(IMessageContract), binding, serviceUri);
32
33          host.Open();
34
35          _ResetEvent.WaitOne();
36        }
37      }).Start();
38      return port;
39    }
40
41    public void Dispose() {
42      _ResetEvent.Set();
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 (OnDataRecieved != null) {
55        OnDataRecieved(this, e);
56      }
57    }
58  }
59}
Note: See TracBrowser for help on using the repository browser.