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

Last change on this file since 13556 was 13556, checked in by thasling, 5 years ago

new hive project

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