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 | {
|
---|
11 | public class WcfMessageService : IMessageService
|
---|
12 | {
|
---|
13 | public event EventHandler<MessageRecieveEventArgs> OnDataRecieved;
|
---|
14 |
|
---|
15 | private static ManualResetEvent _ResetEvent = new ManualResetEvent(false);
|
---|
16 |
|
---|
17 | private IMessageContract messageContract = null;
|
---|
18 |
|
---|
19 | public int Init(string ip)
|
---|
20 | {
|
---|
21 | int port = 0;
|
---|
22 | port = FreeTcpPort();
|
---|
23 |
|
---|
24 | messageContract = new MessageContractImpl();
|
---|
25 | messageContract.MessageRecieved += new EventHandler<MessageRecieveEventArgs>(OnMessageRecieved);
|
---|
26 |
|
---|
27 | var serviceUrl = "DistributedGA.svc";
|
---|
28 | new Thread(() =>
|
---|
29 | {
|
---|
30 | var baseUri = new Uri(string.Concat("net.tcp://", ip, ":", port, "/DistributedGA"));
|
---|
31 | var serviceUri = new Uri(baseUri, serviceUrl);
|
---|
32 | NetTcpBinding binding = new NetTcpBinding();
|
---|
33 | //using (var host = new ServiceHost(typeof(MessageContractImpl), serviceUri))
|
---|
34 |
|
---|
35 | using (var host = new ServiceHost(messageContract, serviceUri))
|
---|
36 | {
|
---|
37 | host.AddServiceEndpoint(typeof(IMessageContract), binding, serviceUri);
|
---|
38 |
|
---|
39 | host.Open();
|
---|
40 |
|
---|
41 | _ResetEvent.WaitOne();
|
---|
42 | }
|
---|
43 | }).Start();
|
---|
44 | //close service again:
|
---|
45 | // _ResetEvent.Set();
|
---|
46 | return port;
|
---|
47 | }
|
---|
48 |
|
---|
49 | public void Dispose()
|
---|
50 | {
|
---|
51 | _ResetEvent.Set();
|
---|
52 | }
|
---|
53 |
|
---|
54 | private int FreeTcpPort()
|
---|
55 | {
|
---|
56 | TcpListener l = new TcpListener(IPAddress.Loopback, 0);
|
---|
57 | l.Start();
|
---|
58 | int port = ((IPEndPoint)l.LocalEndpoint).Port;
|
---|
59 | l.Stop();
|
---|
60 | return port;
|
---|
61 | }
|
---|
62 |
|
---|
63 | private void OnMessageRecieved(object sender, MessageRecieveEventArgs e)
|
---|
64 | {
|
---|
65 | if (OnDataRecieved != null)
|
---|
66 | {
|
---|
67 | OnDataRecieved(this, e);
|
---|
68 | }
|
---|
69 | }
|
---|
70 | }
|
---|
71 | }
|
---|