1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Configuration;
|
---|
4 | using System.Linq;
|
---|
5 | using System.ServiceModel;
|
---|
6 | using DistributedGA.Core.Domain;
|
---|
7 | using DistributedGA.Core.Interface;
|
---|
8 |
|
---|
9 | namespace 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 | List<PeerInfo> allPeers = null;
|
---|
18 | List<PeerInfo> peersForMessaging = null;
|
---|
19 |
|
---|
20 | public void Init(PeerInfo source) {
|
---|
21 | serverString = ConfigurationManager.AppSettings["ContactServerURL"];
|
---|
22 | client = CreateClient();
|
---|
23 | myself = source;
|
---|
24 | client.RegisterPeer(source);
|
---|
25 | }
|
---|
26 |
|
---|
27 | public List<PeerInfo> GetPeerList() {
|
---|
28 | //TODO: maybe always request a new list from the contact server so that he can refresh the heartbeat...
|
---|
29 | if (allPeers == null) {
|
---|
30 | allPeers = client.GetPeerList(myself);
|
---|
31 | peersForMessaging = ChoosePeersForMessaging(allPeers);
|
---|
32 | }
|
---|
33 | //return peersForMessaging;
|
---|
34 | return allPeers; //TODO: Enable 10% list communication
|
---|
35 | }
|
---|
36 |
|
---|
37 | public void SendLogToServer(string msg) {
|
---|
38 | client.MakeLog(myself, msg);
|
---|
39 | }
|
---|
40 |
|
---|
41 | private IContactService CreateClient() {
|
---|
42 | var binding = new BasicHttpBinding();
|
---|
43 | var endpoint = new EndpointAddress(serverString);
|
---|
44 | var myChannelFactory = new ChannelFactory<IContactService>(binding, endpoint);
|
---|
45 |
|
---|
46 | IContactService client = null;
|
---|
47 | client = myChannelFactory.CreateChannel();
|
---|
48 | return client;
|
---|
49 | }
|
---|
50 |
|
---|
51 | private List<PeerInfo> ChoosePeersForMessaging(List<PeerInfo> allPeers) {
|
---|
52 | //communicate with 10% of the network
|
---|
53 | int noOfPeers = allPeers.Count / 10;
|
---|
54 | List<int> indexList = GetRandomItemIndexes(noOfPeers, 0, allPeers.Count - 1);
|
---|
55 | List<PeerInfo> res = new List<PeerInfo>();
|
---|
56 | foreach (int index in indexList) {
|
---|
57 | res.Add(allPeers.ElementAt(index));
|
---|
58 | }
|
---|
59 | return allPeers;
|
---|
60 | }
|
---|
61 |
|
---|
62 | private List<int> GetRandomItemIndexes(int noOfItems, int minValue, int maxValue) {
|
---|
63 | List<int> res = new List<int>();
|
---|
64 | Random rnd = new Random();
|
---|
65 | int tmp = -1;
|
---|
66 | while (res.Count < noOfItems) {
|
---|
67 | tmp = rnd.Next(minValue, maxValue);
|
---|
68 | if (!res.Contains(tmp)) {
|
---|
69 | res.Add(tmp);
|
---|
70 | }
|
---|
71 | }
|
---|
72 | return res;
|
---|
73 | }
|
---|
74 |
|
---|
75 | }
|
---|
76 | }
|
---|