Free cookie consent management tool by TermsFeed Policy Generator

source: branches/thasling/DistributedGA/DistributedGA.Core/Implementation/WcfMessageService.cs @ 13887

Last change on this file since 13887 was 13887, checked in by thasling, 8 years ago

prepared protoype for next meeting

File size: 2.2 KB
Line 
1using System;
2using System.Net;
3using System.Net.Sockets;
4using System.ServiceModel;
5using System.Threading;
6using DistributedGA.Core.Domain;
7using DistributedGA.Core.Interface;
8
9namespace 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}
Note: See TracBrowser for help on using the repository browser.