1 | using System;
|
---|
2 | using System.Net;
|
---|
3 | using System.Net.Sockets;
|
---|
4 | using System.ServiceModel;
|
---|
5 | using System.Threading;
|
---|
6 | using DistributedGA.Core.Domain;
|
---|
7 | using DistributedGA.Core.Interface;
|
---|
8 |
|
---|
9 | namespace 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 = 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("http://", ip, ":", port, "/DistributedGA"));
|
---|
27 | var serviceUri = new Uri(baseUri, serviceUrl);
|
---|
28 | BasicHttpBinding binding = new BasicHttpBinding();
|
---|
29 | //using (var host = new ServiceHost(typeof(MessageContractImpl), serviceUri))
|
---|
30 |
|
---|
31 | using (var host = new ServiceHost(messageContract, serviceUri)) {
|
---|
32 | host.AddServiceEndpoint(typeof(IMessageContract), binding, serviceUri);
|
---|
33 |
|
---|
34 | host.Open();
|
---|
35 |
|
---|
36 | _ResetEvent.WaitOne();
|
---|
37 | }
|
---|
38 | }).Start();
|
---|
39 | //close service again:
|
---|
40 | // _ResetEvent.Set();
|
---|
41 | return port;
|
---|
42 | }
|
---|
43 |
|
---|
44 | public void Dispose() {
|
---|
45 | _ResetEvent.Set();
|
---|
46 | }
|
---|
47 |
|
---|
48 | private int FreeTcpPort() {
|
---|
49 | TcpListener l = new TcpListener(IPAddress.Loopback, 0);
|
---|
50 | l.Start();
|
---|
51 | int port = ((IPEndPoint)l.LocalEndpoint).Port;
|
---|
52 | l.Stop();
|
---|
53 | return port;
|
---|
54 | }
|
---|
55 |
|
---|
56 | private void OnMessageRecieved(object sender, MessageRecieveEventArgs e) {
|
---|
57 | if (OnPopulationRecieved != null) {
|
---|
58 | OnPopulationRecieved(this, e);
|
---|
59 | }
|
---|
60 | }
|
---|
61 | }
|
---|
62 | }
|
---|