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