Пример #1
0
        private static void InitUdpService()
        {
            var ipAddress = IPAddress.Parse("127.0.0.1");
            int port      = 7000;

            _udpService = new UdpService(ipAddress, port);
        }
Пример #2
0
        /// <summary>
        ///     Constructs with a custom multicast IP and port number
        /// </summary>
        /// <param name="customMulticastIp"></param>
        /// <param name="customPort"></param>
        /// <param name="localIp">The IP of the local network adapter to be used by the client, or null for all adapters</param>
        /// <param name="isStrict">If true, packets which are imperfect in any way will not be processed</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public PsnClient([NotNull] IPAddress customMulticastIp, int customPort, IPAddress localIp = null, bool isStrict = true)
        {
            Trackers = new ReadOnlyDictionary <int, PsnTracker>(_trackers);

            if (customMulticastIp == null)
            {
                throw new ArgumentNullException(nameof(customMulticastIp));
            }
            if (!customMulticastIp.IsIPv4Multicast())
            {
                throw new ArgumentException("Not a valid IPv4 multicast address", nameof(customMulticastIp));
            }
            MulticastIp = customMulticastIp;

            if (customPort < ushort.MinValue + 1 || customPort > ushort.MaxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(customPort), customPort,
                                                      $"customPort must be in range {ushort.MinValue + 1}-{ushort.MaxValue}");
            }

            Port = customPort;

            LocalIp  = localIp ?? IPAddress.Any;
            IsStrict = isStrict;

            _udpService = new UdpService(new IPEndPoint(LocalIp, Port));
        }
        public async Task CanReceiveMulticastPacket()
        {
            var multicastIp = IPAddress.Parse("239.0.0.1");
            var ep          = new IPEndPoint(IPAddress.Loopback, UdpPort);
            var service     = new UdpService(ep);

            service.JoinMulticastGroup(multicastIp);

            service.LocalEndPoint.Should().Be(ep, "because this value was set in the constructor");
            service.MulticastGroups.Should().BeEquivalentTo(new[] { multicastIp }, "because this value was set in the constructor");

            var data = System.Text.Encoding.UTF8.GetBytes("Test");
            var host = new UdpClient();

            service.PacketReceived += (s, e) =>
                                      e.Buffer.Should().BeEquivalentTo(data, "because we should receive the test data exactly");

            using (var monitoredService = service.Monitor())
            {
                service.StartListening();

                int bytesSent = await host.SendAsync(data, data.Length, new IPEndPoint(multicastIp, ep.Port));

                bytesSent.Should().Be(data.Length, "because the test data is this long");

                // Allow some time to receive the packet
                await Task.Delay(100);

                monitoredService.Should().Raise(nameof(service.PacketReceived), "because the event should be raised upon receiving a packet");
            }

            host.Dispose();

            service.Dispose();
        }
Пример #4
0
        private async void Enviar()
        {
            IsBotaoHabilitado = false;
            await UdpService.Broadcast(IP, Port, Send, TempoEspera);

            Vibrar(30);
            IsBotaoHabilitado = true;
        }
Пример #5
0
 static void Main(string[] args)
 {
     var udpService = new UdpService();
     while (true)
     {
         udpService.Listen().Wait();
     }
 }
Пример #6
0
        /// <summary>
        ///     Constructs with the PosiStageNet default multicast IP and port number
        /// </summary>
        /// <param name="localIp">The IP of the local network adapter to be used by the client, or null for all adapters</param>
        /// <param name="isStrict">If true, packets which are imperfect in any way will not be processed</param>
        public PsnClient(IPAddress localIp = null, bool isStrict = true)
        {
            Trackers = new ReadOnlyDictionary <int, PsnTracker>(_trackers);

            MulticastIp = DefaultMulticastIp;
            Port        = DefaultPort;
            LocalIp     = localIp ?? IPAddress.Any;
            IsStrict    = isStrict;

            _udpService = new UdpService(new IPEndPoint(LocalIp, Port));
        }
Пример #7
0
        /// <summary>
        ///     Constructs with the PosiStageNet default multicast IP and port number
        /// </summary>
        /// <param name="localIp">IP of local network adapter to listen for multicast packets using</param>
        /// <param name="isStrict">If true, packets which are imperfect in any way will not be processed</param>
        public PsnClient([NotNull] IPAddress localIp, bool isStrict = true)
        {
            RemoteEndPoints = new ReadOnlyDictionary <IPEndPoint, EndPointData>(_endpoints);

            MulticastIp = DefaultMulticastIp;
            Port        = DefaultPort;
            LocalIp     = localIp;
            IsStrict    = isStrict;

            _udpService = new UdpService(new IPEndPoint(LocalIp, Port));
        }
Пример #8
0
        private async void Buscar(object ob)
        {
            if (string.IsNullOrEmpty(EtSend.Text))
            {
                await _broadcastUDPPage.DisplayAlert("Erro", "Preencha o campo Comando", "Fechar");

                return;
            }
            DesabilitarBotao(BtnBuscar);
            await UdpService.Broadcast(comando : EtSend.Text, timer : int.Parse(Tempo.Value.ToString()));

            HabilitarBotao(BtnBuscar);
        }
Пример #9
0
        private async void Testar(object obj)
        {
            DesabilitarBotao(BtnTestarBotao);

            bool isValidos = await ValidarCampos();

            if (!isValidos)
            {
                return;
            }

            await UdpService.Broadcast(comando : Comando.Send, port : Comando.Port, ip : Comando.IP, timer : int.Parse(StTempoEspera.Value.ToString()));

            Vibrar(30);

            HabilitarBotao(BtnTestarBotao);
        }
Пример #10
0
        private PsnServer([NotNull] string systemName, [NotNull] IPAddress multicastIp, int port, double dataSendFrequency,
                          double infoSendFrequency, [CanBeNull] IPAddress localIp)
        {
            if (systemName == null)
            {
                throw new ArgumentNullException(nameof(systemName));
            }
            SystemName = systemName;

            if (multicastIp == null)
            {
                throw new ArgumentNullException(nameof(multicastIp));
            }
            if (!multicastIp.IsIPv4Multicast())
            {
                throw new ArgumentException("Not a valid IPv4 multicast address", nameof(multicastIp));
            }

            if (port < ushort.MinValue + 1 || port > ushort.MaxValue)
            {
                throw new ArgumentOutOfRangeException(nameof(port), port,
                                                      $"customPort must be in range {ushort.MinValue + 1}-{ushort.MaxValue}");
            }

            _targetEndPoint = new IPEndPoint(multicastIp, port);

            if (dataSendFrequency <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(dataSendFrequency), dataSendFrequency,
                                                      "dataSendFrequency must be greater than 0");
            }
            DataSendFrequency = dataSendFrequency;

            if (infoSendFrequency <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(infoSendFrequency), infoSendFrequency,
                                                      "infoSendFrequency must be greater than 0");
            }

            InfoSendFrequency = infoSendFrequency;

            LocalIp = localIp ?? IPAddress.Any;

            _udpService = new UdpService(new IPEndPoint(LocalIp, 0));
        }
Пример #11
0
        public void CanManageListeningState()
        {
            var service = new UdpService(new IPEndPoint(IPAddress.Loopback, UdpPort));

            service.IsListening.Should().BeFalse("because the service is not listening");

            service.Invoking(s => s.StopListeningAsync())
            .Should().Throw <InvalidOperationException>("because the service is not listening");

            service.StartListening();

            service.IsListening.Should().BeTrue("because the service is listening");

            service.Invoking(s => s.StartListening())
            .Should().Throw <InvalidOperationException>("because the service is already listening");

            service.Dispose();
        }
Пример #12
0
        static void Main(string[] args)
        {
            UdpService udpService = null;

#if debug
            udpService = new UdpService("127.0.0.1", "9000", "127.0.0.1", "8000");
#else
            udpService = new UdpService("182.168.100.50", "9000", "182.168.100.48", "8000");
#endif
            Console.WriteLine("udp接受、短信服务开启");
            Console.ReadKey();
            Console.WriteLine("再按就退出了");
            Console.ReadKey();
            Console.WriteLine("再按就退出了");
            Console.ReadKey();
            Console.WriteLine("再按就退出了");
            Console.ReadKey();
            Console.WriteLine("再按就退出了");
            Console.ReadKey();
            Console.WriteLine("再按就退出了");
            Console.ReadKey();
        }
Пример #13
0
 public CoreMessager()
 {
     UdpService = new UdpService(8000, "127.0.0.1");
 }
Пример #14
0
        /// <summary>
        /// Настройка обработчика команд
        /// </summary>
        private static void SetupCommands(CommandHandler commandHandler)
        {
            commandHandler.Add(new Command("set_protocol", (string[] args) =>
            {
                var networkService   = Toolbox.GetTool <INetworkService>();
                IPAddress recieverIp = null;
                int recieverPort     = -1;
                int listenerPort     = -1;

                if (networkService != null)
                {
                    recieverIp   = networkService.RecieverIp;
                    recieverPort = networkService.RecieverPort;
                    listenerPort = networkService.ListenerPort;

                    networkService.Dispose();
                    Toolbox.Remove(networkService);
                }
                else
                {
                    recieverIp = IPAddress.Loopback;
                }

                if (args.Length > 0)
                {
                    switch (args[0])
                    {
                    case "udp":
                        var udpService = new UdpService();
                        udpService.SetRecieverInfo(recieverIp.ToString(), recieverPort);

                        if (listenerPort >= 0)
                        {
                            udpService.SetListenerPort(listenerPort);
                        }

                        Toolbox.Add(udpService);
                        Print.Log("Установлен протокол UDP", Color.DarkBlue);
                        break;

                    case "tcp":
                        Print.Log("Установлен протокол TCP", Color.DarkBlue);
                        var tcpService = new TcpService();
                        tcpService.SetRecieverInfo(recieverIp.ToString(), recieverPort);

                        if (listenerPort >= 0)
                        {
                            tcpService.SetListenerPort(listenerPort);
                        }

                        Toolbox.Add(tcpService);
                        break;

                    default:
                        var udpServiceDefault = new UdpService();
                        udpServiceDefault.SetRecieverInfo(recieverIp.ToString(), recieverPort);

                        if (listenerPort >= 0)
                        {
                            udpServiceDefault.SetListenerPort(listenerPort);
                        }

                        Toolbox.Add(udpServiceDefault);
                        Print.LogWarning("По умолчанию выбран протокол UDP");
                        break;
                    }
                }
                else
                {
                    var udpServiceDefault = new UdpService();
                    udpServiceDefault.SetRecieverInfo(recieverIp.ToString(), recieverPort);

                    if (listenerPort >= 0)
                    {
                        udpServiceDefault.SetListenerPort(listenerPort);
                    }

                    Toolbox.Add(udpServiceDefault);
                    Print.LogWarning("По умолчанию выбран протокол UDP");
                }
            })).Invoke(new string[] { "tcp" });

            commandHandler.Add(new Command("set_reciever_ip", (string[] args) =>
            {
                var networkService = Toolbox.GetTool <INetworkService>();

                if (networkService == null)
                {
                    Print.LogWarning("Протокол не установлен!");
                    return;
                }

                if (args.Length > 0)
                {
                    networkService.SetRecieverIp(args[0]);
                    return;
                }

                Print.LogError("Отсутствует аргумент адреса!");
            }));

            commandHandler.Add(new Command("set_reciever_port", (string[] args) =>
            {
                var networkService = Toolbox.GetTool <INetworkService>();

                if (networkService == null)
                {
                    Print.LogWarning("Протокол не установлен!");
                    return;
                }

                if (args.Length > 0)
                {
                    var numList = CommandsExtensions.ParseInt(args);

                    if (numList.Count > 0)
                    {
                        networkService.SetRecieverPort(numList[0]);
                        return;
                    }
                }

                Print.LogError("Отсутствует аргумент порта!");
            }));

            commandHandler.Add(new Command("set_listener_port", (string[] args) =>
            {
                var networkService = Toolbox.GetTool <INetworkService>();

                if (networkService == null)
                {
                    Print.LogWarning("Протокол не установлен!");
                    return;
                }

                if (args.Length > 0)
                {
                    var numList = CommandsExtensions.ParseInt(args);

                    if (numList.Count > 0)
                    {
                        networkService.SetListenerPort(numList[0]);
                        return;
                    }
                }

                Print.LogError("Отсутствует аргумент порта!");
            }));

            commandHandler.Add(new Command("send_ping", (string[] args) =>
            {
                var networkService = Toolbox.GetTool <INetworkService>();

                if (networkService == null)
                {
                    Print.LogWarning("Протокол не установлен!");
                    return;
                }

                networkService.Send($"ping from {Process.GetCurrentProcess().Id}");
            }));

            commandHandler.Add(new Command("show_msbuf", (string[] args) =>
            {
                var msbuf = Toolbox.GetTool <MessageBuffer>();

                if (msbuf == null)
                {
                    Print.LogError("Буфер сообщений отсутствует.");
                    return;
                }

                if (msbuf.Messages.Count == 0)
                {
                    Print.Log("Сообщений нет.", Color.DarkBlue);
                    return;
                }

                foreach (var str in msbuf.QueryQueue())
                {
                    Print.Log(str, Color.Blue);
                }
            }));

            commandHandler.Handle("set_reciever_port : 7777");
            commandHandler.Handle("set_listener_port : 7777");
        }
Пример #15
0
        /// <summary>
        /// 构造方法
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            //初始化存储目录
            System.IO.Directory.CreateDirectory("library");

            #region 初始化数据库

            #region sqlite文件检查
            //try {
            //    bool isTableExists;
            //    using (var sqlite = new SQLiteConnection("Data Source=data.db;Version=3;")) {
            //        sqlite.Open();
            //        var tableExists = new SQLiteCommand("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='TagLibrary';", sqlite);
            //        var result = tableExists.ExecuteReader();
            //        result.Read();
            //        if (result.GetInt32(0) == 0) {
            //            isTableExists = false;
            //        } else {
            //            isTableExists = true;
            //        }
            //        sqlite.Close();
            //    }

            //    if (!isTableExists) {
            //        GC.Collect();
            //        GC.WaitForPendingFinalizers();
            //        File.Delete("data.db");
            //        using (var sqlite = new SQLiteConnection("Data Source=data.db;Version=3;")) {
            //            sqlite.Open();
            //            var createTable = new SQLiteCommand("CREATE TABLE IF NOT EXISTS TagLibrary (Major INT, Minor INT, Build INT);", sqlite);
            //            createTable.ExecuteNonQuery();
            //            sqlite.Close();
            //        }
            //    }
            //} catch {
            //    GC.Collect();
            //    GC.WaitForPendingFinalizers();
            //    File.Delete("data.db");
            //    using (var sqlite = new SQLiteConnection("Data Source=data.db;Version=3;")) {
            //        sqlite.Open();
            //        var createTable = new SQLiteCommand("CREATE TABLE IF NOT EXISTS TagLibrary (Major INT, Minor INT, Build INT);", sqlite);
            //        createTable.ExecuteNonQuery();
            //        sqlite.Close();
            //    }
            //}
            #endregion

            //初始化SqlSugar
            db = new SqlSugarClient(new ConnectionConfig()
            {
                DbType           = DbType.Sqlite,
                ConnectionString = "Data Source=data.db;Version=3;",
                InitKeyType      = InitKeyType.Attribute
            });
            //检查版本并进行版本迁移工作
            CheckVersion();
            CodeFirst();
            #endregion

            #region 初始化字段
            version = string.Format("{0}.{1}.{2:000000}", versionMajor, versionMinor, versionBuild);
            #endregion

            #region 从数据库中读取数据

            //初始化文件列表
            files = db.Queryable <FileInfo>().ToList();
            fileList.ItemsSource = new BindingList <FileInfo>();
            foreach (var item in files)
            {
                (fileList.ItemsSource as BindingList <FileInfo>).Add(item);
            }

            //初始化文件格式列表
            //var fileFormats = new BindingList<TreeViewItem>();
            //fileList.GroupBy(fileInfo => fileInfo.Format)
            //    .Select(fileInfo => fileInfo.Key)
            //    .ToList()
            //    .ForEach(format => fileFormats.Add(new TreeViewItem() {
            //        Header = format
            //    }));
            //tagTree.ItemsSource = fileFormats;

            //初始化Tag列表
            tags         = db.Queryable <TagInfo>().ToList();
            tagTree.Tags = tags;


            //初始化映射列表
            mappers = db.Queryable <FileTagMapper>().ToList();

            hostList.ItemsSource = new BindingList <HostInfo>(new List <HostInfo>()
            {
                new HostInfo("localhost", "online")
            });



            #endregion


            #region 网络部分
            UdpService.HostListChanged += (_sender, _e) => {
                hostList.Dispatcher.Invoke(() => {
                    if (_e.IsAdd)
                    {
                        (hostList.ItemsSource as BindingList <HostInfo>).Add(_e.HostInfo);
                    }
                    else
                    {
                        (hostList.ItemsSource as BindingList <HostInfo>).Remove(_e.HostInfo);
                    }
                });
            };

            HttpService.FileInfos      = files;
            HttpService.TagInfos       = tags;
            HttpService.FileTagMappers = mappers;
            if (HttpService.StartHttpService())
            {
                httpStatus.Content = "服务已开启, 端口号为:" + HttpService.Port;
            }
            else
            {
                httpStatus.Content = "服务未开启";
            }

            UdpService.HttpPort = HttpService.Port;
            if (UdpService.StartSendHeartBeat() && UdpService.StartReceive())
            {
                udpStatus.Content = "服务已开启";
            }
            else
            {
                udpStatus.Content = "服务未开启";
            }
            #endregion
        }