Пример #1
0
 internal byte[] KeepRequest(byte[] req)
 {
     if (MqClient == null)
     {
         MqClient = new NettyClient();
         MqClient.Start(host, port);
     }
     MqClient.Send(req);
     return(MqClient.GetData().Message as byte[]);
 }
Пример #2
0
        private async Task <NettyClient> GetOrCreateReplyRemotingClientAsync(string replyAddress, IPEndPoint replyEndpoint)
        {
            return(await _remotingClientDict.GetOrAdd(replyAddress, new Lazy <Task <NettyClient> >(async() =>
            {
                var client = new NettyClient(replyEndpoint, null);

                await client.StartAsync();

                return client;
            })).Value);
        }
Пример #3
0
        /// <summary>
        /// 请求获取
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        internal byte[] Request(byte[] req)
        {
            NettyClient client = new NettyClient();

            client.Start(host, port);
            client.Send(req);
            var result = client.GetData().Message as byte[];

            client.Close();
            return(result);
        }
Пример #4
0
        public static async void Initialize()
        {
            Logger = new Logger();
            Logger.Log(
                $"Starting [{DateTime.Now.ToLongTimeString()} - {ServerUtils.GetOsName()}]...",
                null);

            Configuration = new Configuration();
            Configuration.Initialize();

            ClusterClient = new ClusterClient();

            Sessions = new Sessions();

            Netty       = new NettyService();
            NettyClient = new NettyClient();

            await Task.Run(Netty.RunServerAsync);

            await Task.Run(NettyClient.RunClientAsync);
        }
Пример #5
0
        static void Main(string[] args)
        {
            NettyPool.SessionHandler       = new Handler();
            NettyPool.ClientSessionHandler = new ClientHandler();

            NettyPool.AddTcpBind("127.0.0.1", 8001);

            clientA = new NettyClient(port: 8001);
            clientA.Connect();

            clientB = new NettyClient(port: 8001);
            clientB.Connect();

            System.Threading.Thread.Sleep(1000);

            log.Error("数量 " + NettyPool.Sessions.Count);

            sendtask = new SendTask();

            ThreadPool.AddGlobTimerTask(sendtask);

            Console.ReadLine();
        }
 public HeartBeatHandler(NettyClient nettyClient)
 {
     this._nettyClient = nettyClient;
 }
Пример #7
0
        public async Task Should_Communicates_Between_Server_And_Client()
        {
            //Arrange
            var serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9019);

            var serverSetting = new NettyServerSetting(
                channel =>
            {
                var pipeline = channel.Pipeline;

                pipeline.AddLast(typeof(LengthFieldPrepender).Name, new LengthFieldPrepender(2));
                pipeline.AddLast(typeof(LengthFieldBasedFrameDecoder).Name, new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                pipeline.AddLast(typeof(RequestEncoder).Name, new RequestEncoder());
                pipeline.AddLast(typeof(RequestDecoder).Name, new RequestDecoder());
                pipeline.AddLast(typeof(ServerHandler).Name, new ServerHandler(ObjectContainer.Resolve <ServerMessageBox>()));
            }
                );
            var server = new NettyServer(serverEndPoint, serverSetting);

            server.Start();

            var clientChannelHandlerTypes = new List <ChannelHandlerInstance>();

            clientChannelHandlerTypes.Add(new ChannelHandlerInstance()
            {
                Type = typeof(ClientHandler), Args = new List <object>()
                {
                    ObjectContainer.Resolve <ClientMessageBox>()
                }
            });

            var clientSetting = new NettyClientSetting(
                channel =>
            {
                var pipeline = channel.Pipeline;

                pipeline.AddLast(typeof(LengthFieldPrepender).Name, new LengthFieldPrepender(2));
                pipeline.AddLast(typeof(LengthFieldBasedFrameDecoder).Name, new LengthFieldBasedFrameDecoder(ushort.MaxValue, 0, 2, 0, 2));
                pipeline.AddLast(typeof(RequestEncoder).Name, new RequestEncoder());
                pipeline.AddLast(typeof(RequestDecoder).Name, new RequestDecoder());
                pipeline.AddLast(typeof(ClientHandler).Name, new ClientHandler(ObjectContainer.Resolve <ClientMessageBox>()));
            }
                );
            var client = new NettyClient(serverEndPoint, clientSetting);
            await client.StartAsync();

            var request = new Request()
            {
                Code = 1,
                Body = Encoding.UTF8.GetBytes("test")
            };

            //Act
            await client.Channel.WriteAndFlushAsync(request);

            await Task.Delay(300);

            //Assert
            var serverMessageBox = ObjectContainer.Resolve <ServerMessageBox>();
            var messages         = await serverMessageBox.GetAllAsync();

            messages.Count.ShouldBe(1);
            messages.Select(m => m as Request).FirstOrDefault(m => m.Code == request.Code).ShouldNotBeNull();
        }
Пример #8
0
        public Main(Arguments args)
        {
            this.log             = Log.Logger;
            this.fileStoragePath = args.FileStoragePath;

            // Clean up temp folder
            string tempFolder = Path.Combine(this.fileStoragePath, "tmp");

            Directory.CreateDirectory(tempFolder);
            Directory.GetDirectories(tempFolder).ToList().ForEach(x => Directory.Delete(x, true));

            if (!string.IsNullOrEmpty(args.VideoSystem))
            {
                switch (args.VideoSystem.ToLower())
                {
                case "omx":
                    this.videoSystem = VideoSystems.OMX;
                    break;

                default:
                    throw new ArgumentException("Invalid video system type");
                }
            }
            else
            {
                this.videoSystem = VideoSystems.None;
            }

            if (args.AudioSystem && this.videoSystem != VideoSystems.None)
            {
                throw new ArgumentException("Cannot support both audio and video system concurrently");
            }

            if (this.videoSystem != VideoSystems.None)
            {
                // Disable console log output
                this.log.Information("Video System, turning off console logging and cursor");

                //FIXME
                //var logConfig = LogManager.Configuration;
                //var consoleTargets = new List<string>();
                //consoleTargets.AddRange(logConfig.AllTargets
                //    .OfType<NLog.Targets.ColoredConsoleTarget>()
                //    .Select(x => x.Name));
                //consoleTargets.AddRange(logConfig.AllTargets
                //    .OfType<NLog.Targets.ConsoleTarget>()
                //    .Select(x => x.Name));
                //foreach (var loggingRule in logConfig.LoggingRules)
                //{
                //    loggingRule.Targets
                //        .Where(x => consoleTargets.Contains(x.Name) || consoleTargets.Contains(x.Name + "_wrapped"))
                //        .ToList()
                //        .ForEach(x => loggingRule.Targets.Remove(x));
                //}
                //LogManager.Configuration = logConfig;

                Console.CursorVisible = false;
                Console.Clear();
            }

            this.loadedSounds   = new Dictionary <string, Sound>();
            this.currentBgTrack = -1;
            this.random         = new Random();
            this.disposeList    = new List <IDisposable>();
            this.serialPorts    = new Dictionary <int, SerialPort>();

            string fileStoragePath = Path.GetFullPath(args.FileStoragePath);

            Directory.CreateDirectory(fileStoragePath);

            this.soundEffectPath = Path.Combine(fileStoragePath, FileTypes.AudioEffect.ToString());
            this.trackPath       = Path.Combine(fileStoragePath, FileTypes.AudioTrack.ToString());
            this.videoPath       = Path.Combine(fileStoragePath, FileTypes.Video.ToString());

            this.autoStartBackgroundTrack = args.BackgroundTrackAutoStart;

            // Try to read instance id from disk
            try
            {
                using (var f = File.OpenText(Path.Combine(fileStoragePath, "MonoExpander_InstanceId.txt")))
                {
                    this.instanceId = f.ReadLine();
                }
            }
            catch
            {
                // Generate new
                this.instanceId = Guid.NewGuid().ToString("n");

                using (var f = File.CreateText(Path.Combine(fileStoragePath, "MonoExpander_InstanceId.txt")))
                {
                    f.WriteLine(this.instanceId);
                    f.Flush();
                }
            }

            this.log.Information("Instance Id {0}", this.instanceId);
            this.log.Information("Video Path {0}", this.videoPath);
            this.log.Information("Track Path {0}", this.trackPath);
            this.log.Information("FX Path {0}", this.soundEffectPath);

            this.backgroundAudioTracks = new List <string>();
            if (!string.IsNullOrEmpty(args.BackgroundTracksPath))
            {
                this.backgroundAudioTracks.AddRange(Directory.GetFiles(args.BackgroundTracksPath, "*.wav"));
                this.backgroundAudioTracks.AddRange(Directory.GetFiles(args.BackgroundTracksPath, "*.mp3"));
            }

            if (args.AudioSystem)
            {
                this.log.Information("Initializing FMOD sound system");
                this.fmodSystem = new LowLevelSystem();

                this.fxGroup  = this.fmodSystem.CreateChannelGroup("FX");
                this.trkGroup = this.fmodSystem.CreateChannelGroup("Track");
                this.bgGroup  = this.fmodSystem.CreateChannelGroup("Background");
            }

            if (SupersonicSound.Wrapper.Util.IsUnix)
            {
                this.log.Information("Initializing PiFace");

                try
                {
                    this.piFace = new PiFaceDigitalDevice();

                    // Setup events
                    foreach (var ip in this.piFace.InputPins)
                    {
                        ip.OnStateChanged += (s, e) =>
                        {
                            SendInputMessage(e.pin.Id, e.pin.State);
                        };

                        // Send current state
                        SendInputMessage(ip.Id, ip.State);
                    }
                }
                catch (Exception ex)
                {
                    this.log.Warning(ex, "Failed to initialize PiFace");
                }
            }

            if (!string.IsNullOrEmpty(args.SerialPort0) && args.SerialPort0BaudRate > 0)
            {
                this.log.Information("Initialize serial port 0 ({0}) for {1} bps", args.SerialPort0, args.SerialPort0BaudRate);

                var serialPort = new SerialPort(args.SerialPort0, args.SerialPort0BaudRate);

                serialPort.Open();

                this.serialPorts.Add(0, serialPort);
            }

            this.log.Information("Initializing ExpanderCommunication client");

            this.connections = new List <Tuple <IClientCommunication, MonoExpanderClient> >();
            foreach (var server in args.Servers)
            {
                var client = new MonoExpanderClient(this);

#if SIGNALR
                var communication = new SignalRClient(
                    host: server.Host,
                    port: server.Port,
                    instanceId: InstanceId,
                    dataReceivedAction: (t, d) => DataReceived(client, t, d));
#endif
#if NETTY
                var communication = new NettyClient(
                    logger: this.log,
                    host: server.Host,
                    port: server.Port,
                    instanceId: InstanceId,
                    dataReceivedAction: (t, d) => DataReceived(client, t, d),
                    connectedAction: () => SendMessage(new Ping()));
#endif
                this.connections.Add(Tuple.Create((IClientCommunication)communication, client));

                Task.Run(async() => await communication.StartAsync()).Wait();
            }
        }
Пример #9
0
 public ClientHandler(NettyClient nettyClient)
 {
     this._nettyClient = nettyClient;
 }