コード例 #1
0
        protected override void OnStart(string[] args)
        {
            try
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        _tcpServiceHost = new TcpServerHelper2(IPAddress.Parse(CommandLineArgs.BindIpAddress));
                        Program.MainLogSystem.WriteLogEntry("Binded to " + _tcpServiceHost.ListenAddress);
                        _tcpServiceHost.OnLogMessage += (client, message) =>
                        {
                            if (client != null && client.ClientSocket != null && client.ClientSocket.Connected)
                                message = "Log from: " + client.ClientSocket.Client.RemoteEndPoint.ToString() + " " + message;
                            Program.MainLogSystem.WriteLogEntry(message);
                        };
                        _tcpServiceHost.Online();
                        _udpService = new UdpHelper();
                        _udpService.OnReceiveData += (endPoint, data) =>
                        {
                            try
                            {
                                Packet packet = new Packet(data);
                                if (packet.Opcode == Opcodes.ServerSearch)
                                {
                                    string addr = _tcpServiceHost.ListenAddress.ToString();
                                    _udpService.SendPacket(endPoint.Address, new Packet(Guid.Empty, Opcodes.ServerFound, addr));
                                    Program.MainLogSystem.WriteLogEntry("Broadcast query accepted from " + endPoint.Address);
                                }
                            }
                            catch (Exception ex)
                            {
                                Program.MainLogSystem.WriteLogEntry("UdpHelper OnReceiveData exception: " + ex.Message);
                                throw;
                            }
                        };
                        _udpService.Start();
                    }
                    catch (Exception ex)
                    {
                        Program.MainLogSystem.WriteLogEntry("OnStart exception: "+ex.Message);
                        throw;
                    }


                }, TaskCreationOptions.LongRunning).ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        if (task.Exception != null)
                            throw task.Exception;
                    }
                }, TaskContinuationOptions.OnlyOnFaulted);
            }
            catch
            {
                throw;
            }

        }
コード例 #2
0
ファイル: ClientProcessor.cs プロジェクト: Winsor/ITInfra
        public void ConnectService()
        {
            MiniSplash_TF splash = new MiniSplash_TF(Resources.load1)
            {
                Text = @"Запуск приложения",
                StatusText = @"Поиск сервера уведомлений"
            };
            UdpHelper udpService = new UdpHelper(IpDefaultPorts.DefaultUdpResponsePort);
            udpService.OnReceiveData += (endPoint, data) =>
            {
                Packet packet = new Packet(data);
                if (packet.Opcode == Opcodes.ServerFound)
                {
                    _serverAddress = packet.Data;
                }
            };
            splash.WorkingFunction = () =>
            {
                try
                {
                    List<string> broadcasts = new List<string>();
                    foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces())
                    {
                        IPInterfaceProperties properties = netif.GetIPProperties();
                        foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses)
                        {
                            if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                                continue;
                            if (unicast.IPv4Mask == null)
                                continue;
                            byte[] ipAdressBytes = unicast.Address.GetAddressBytes();
                            byte[] subnetMaskBytes = unicast.IPv4Mask.GetAddressBytes();
                            byte[] broadcastAddress = new byte[ipAdressBytes.Length];
                            for (int i = 0; i < broadcastAddress.Length; i++)
                            {
                                broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
                            }
                            broadcasts.Add(string.Join(".", broadcastAddress));
                        }
                    }
                    _serverAddress = string.Empty;
                    udpService.Start();
                    bool finished = false;
                    int trying = 1;
                    while (!finished && trying <= 5)
                    {
                        splash.StatusText = @"Поиск сервера уведомлений, попытка: " + trying;
                        broadcasts.ForEach(ba =>
                        {
                            UdpClient client = new UdpClient();
                            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                            IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ba), IpDefaultPorts.DefaultUdpListenPort);
                            byte[] bytes = Encoding.ASCII.GetBytes(new Packet(Guid.Empty, Opcodes.ServerSearch, string.Empty).Pack());
                            client.Send(bytes, bytes.Length, ip);
                            client.Close();
                            Thread.Sleep(200);
                        });
                        if (_serverAddress != string.Empty)
                            finished = true;
                        trying++;
                    }
                }
                catch (Exception ex)
                {
                    OnMessageShow(ex.Message);
                    throw;
                }
            };
            splash.ShowDialog();
#if DEBUG
            _serverAddress = "10.100.1.47";
#endif
            if (_serverAddress != string.Empty)
            {
               Reconnect(_serverAddress);
            }
            else
            {
                OnMessageShow("Сервис уведомлений не найден, пытаемся соедениться напрямую!");
                Reconnect("10.100.1.21");
            }
            udpService.Stop();
        }
コード例 #3
0
ファイル: MainClientHost.cs プロジェクト: Winsor/ITInfra
     //private void ServerHelperInit()
     //   {
     //       _serverHelper = new TcpServerHelper(null,LocalServerPort);
     //       _serverHelper.OnBeforeStop += Unsubscribe;
     //       _serverHelper.OnReceiveData += (info, data) =>
     //       {
     //           Packet packet = new Packet(data);
     //           if (packet.Opcode == Opcodes.Invalid)
     //               return;
     //           if (packet.Opcode == Opcodes.ServerShutdown)
     //           {
     //               _serverHelper.Offline();
     //               MessageBox.Show("server going offline");
     //               return;
     //           }
     //           if (packet.Opcode == Opcodes.NotifyAll)
     //           {
     //               NotifyData nData = new NotifyData(packet.Data);
     //               MessageBox.Show(nData.Data);
     //               return;
     //           }
     //       };
     //       _serverHelper.Online();
     //   }



        private void button1_Click(object sender, EventArgs e)
        {
            MiniSplash_TF splash = new MiniSplash_TF(Resources.load4)
            {
                Text = @"Запуск приложения",
                StatusText = @"Поиск сервера уведомлений"
            };
            UdpHelper udpService = new UdpHelper(IpDefaultPorts.DefaultUdpResponsePort);
            udpService.OnReceiveData += (endPoint, data) =>
            {
                Packet packet = new Packet(data);
                if (packet.Opcode == Opcodes.ServerFound)
                {
                    _serverAddress = packet.Data;
                }
            };
            splash.WorkingFunction = () =>
            {
                try
                {
                    List<string> broadcasts = new List<string>();
                    foreach (NetworkInterface netif in NetworkInterface.GetAllNetworkInterfaces())
                    {
                        IPInterfaceProperties properties = netif.GetIPProperties();
                        foreach (UnicastIPAddressInformation unicast in properties.UnicastAddresses)
                        {
                            if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                                continue;
                            if (unicast.IPv4Mask == null)
                                continue;
                            byte[] ipAdressBytes = unicast.Address.GetAddressBytes();
                            byte[] subnetMaskBytes = unicast.IPv4Mask.GetAddressBytes();
                            byte[] broadcastAddress = new byte[ipAdressBytes.Length];
                            for (int i = 0; i < broadcastAddress.Length; i++)
                            {
                                broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));
                            }
                            broadcasts.Add(string.Join(".", broadcastAddress));
                        }
                    }
                    _serverAddress = string.Empty;
                    udpService.Start();
                    bool finished = false;
                    int trying = 1;
                    while (!finished && trying <= 5)
                    {
                        splash.StatusText = @"Поиск сервера уведомлений, попытка: " + trying;
                        broadcasts.ForEach(ba =>
                        {
                            UdpClient client = new UdpClient();
                            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                            IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ba), IpDefaultPorts.DefaultUdpListenPort);
                            byte[] bytes = Encoding.ASCII.GetBytes(new Packet(Guid.Empty, Opcodes.ServerSearch, string.Empty).Pack());
                            client.Send(bytes, bytes.Length, ip);
                            client.Close();
                            Thread.Sleep(200);
                        });
                        if (_serverAddress != string.Empty)
                            finished = true;
                        trying++;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    throw;
                }
            };
            splash.ShowDialog(this);
            if (_serverAddress != string.Empty)
            {
                if (_clientHelper.Client.Connected)
                {
                    _clientHelper.SendData(new Packet(Guid.NewGuid(), Opcodes.Unsubscribe, Appid.ToString()));
                    _clientHelper.Stop();
                }
                if (_clientHelper.Connect(_serverAddress, IpDefaultPorts.DefaultTcpServerListenerPort))
                {
                    _clientHelper.Start();
                }
                else
                {
                    MessageBox.Show("not connect to " + _serverAddress);
                }
            }
            else
            {
                MessageBox.Show("service not found");
            }
            udpService.Stop();
        }