[13538] | 1 | using System;
|
---|
[13524] | 2 | using System.Net;
|
---|
| 3 | using System.Net.Sockets;
|
---|
| 4 | using System.ServiceModel;
|
---|
| 5 | using System.Threading;
|
---|
[13538] | 6 | using DistributedGA.Core.Domain;
|
---|
| 7 | using DistributedGA.Core.Interface;
|
---|
[13524] | 8 |
|
---|
[13887] | 9 | namespace DistributedGA.Core.Implementation
|
---|
| 10 | {
|
---|
| 11 | public class WcfMessageService : IMessageService
|
---|
| 12 | {
|
---|
| 13 | public event EventHandler<MessageRecieveEventArgs> OnDataRecieved;
|
---|
[13524] | 14 |
|
---|
[13887] | 15 | private static ManualResetEvent _ResetEvent = new ManualResetEvent(false);
|
---|
[13524] | 16 |
|
---|
[13887] | 17 | private IMessageContract messageContract = null;
|
---|
[13524] | 18 |
|
---|
[13887] | 19 | public int Init(string ip)
|
---|
| 20 | {
|
---|
| 21 | int port = 0;
|
---|
| 22 | port = FreeTcpPort();
|
---|
[13524] | 23 |
|
---|
[13887] | 24 | messageContract = new MessageContractImpl();
|
---|
| 25 | messageContract.MessageRecieved += new EventHandler<MessageRecieveEventArgs>(OnMessageRecieved);
|
---|
[13524] | 26 |
|
---|
[13887] | 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))
|
---|
[13524] | 34 |
|
---|
[13887] | 35 | using (var host = new ServiceHost(messageContract, serviceUri))
|
---|
| 36 | {
|
---|
| 37 | host.AddServiceEndpoint(typeof(IMessageContract), binding, serviceUri);
|
---|
[13524] | 38 |
|
---|
[13887] | 39 | host.Open();
|
---|
[13524] | 40 |
|
---|
[13887] | 41 | _ResetEvent.WaitOne();
|
---|
| 42 | }
|
---|
| 43 | }).Start();
|
---|
| 44 | //close service again:
|
---|
| 45 | // _ResetEvent.Set();
|
---|
| 46 | return port;
|
---|
[13524] | 47 | }
|
---|
| 48 |
|
---|
[13887] | 49 | public void Dispose()
|
---|
| 50 | {
|
---|
| 51 | _ResetEvent.Set();
|
---|
| 52 | }
|
---|
[13547] | 53 |
|
---|
[13887] | 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 | }
|
---|
[13524] | 62 |
|
---|
[13887] | 63 | private void OnMessageRecieved(object sender, MessageRecieveEventArgs e)
|
---|
| 64 | {
|
---|
| 65 | if (OnDataRecieved != null)
|
---|
| 66 | {
|
---|
| 67 | OnDataRecieved(this, e);
|
---|
| 68 | }
|
---|
| 69 | }
|
---|
[13538] | 70 | }
|
---|
[13524] | 71 | }
|
---|