source: branches/thasling/DistributedGA/DistributedGA.Core/Implementation/WcfPeerListManager.cs @ 13554

Last change on this file since 13554 was 13554, checked in by thasling, 6 years ago

PeerList now is fetched from the server each time the peerlist is needed

File size: 2.1 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Configuration;
4using System.Linq;
5using System.ServiceModel;
6using DistributedGA.Core.Domain;
7using DistributedGA.Core.Interface;
8
9namespace DistributedGA.Core.Implementation {
10  public class WcfPeerListManager : IPeerListManager {
11    private string serverString = null;
12
13    private IContactService client = null;
14
15    private PeerInfo myself = null;
16
17    public void Init(PeerInfo source) {
18      serverString = ConfigurationManager.AppSettings["ContactServerURL"];
19      client = CreateClient();
20      myself = source;
21      client.RegisterPeer(source);
22    }
23
24    public List<PeerInfo> GetPeerList() {
25      var allPeers = client.GetPeerList(myself);
26      var peersForMessaging = ChoosePeersForMessaging(allPeers);
27      //return peersForMessaging;
28      return allPeers; //TODO: Enable 10% list communication
29    }
30
31    public void SendLogToServer(string msg) {
32      client.MakeLog(myself, msg);
33    }
34
35    private IContactService CreateClient() {
36      var binding = new BasicHttpBinding();
37      var endpoint = new EndpointAddress(serverString);
38      var myChannelFactory = new ChannelFactory<IContactService>(binding, endpoint);
39
40      IContactService client = null;
41      client = myChannelFactory.CreateChannel();
42      return client;
43    }
44
45    private List<PeerInfo> ChoosePeersForMessaging(List<PeerInfo> allPeers) {
46      //communicate with 10% of the network
47      int noOfPeers = allPeers.Count / 10;
48      List<int> indexList = GetRandomItemIndexes(noOfPeers, 0, allPeers.Count - 1);
49      List<PeerInfo> res = new List<PeerInfo>();
50      foreach (int index in indexList) {
51        res.Add(allPeers.ElementAt(index));
52      }
53      return allPeers;
54    }
55
56    private List<int> GetRandomItemIndexes(int noOfItems, int minValue, int maxValue) {
57      List<int> res = new List<int>();
58      Random rnd = new Random();
59      int tmp = -1;
60      while (res.Count < noOfItems) {
61        tmp = rnd.Next(minValue, maxValue);
62        if (!res.Contains(tmp)) {
63          res.Add(tmp);
64        }
65      }
66      return res;
67    }
68
69  }
70}
Note: See TracBrowser for help on using the repository browser.