Ejemplo n.º 1
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById <Button>(Resource.Id.myButton);

            button.Text = GetIPAddress().ToString();

            button.Click += delegate
            {
                button.Text = string.Format("{0} clicks!", count++);
            };

            this.drawingView = new DrawingView(this.ApplicationContext);

            this.AddContentView(this.drawingView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.FillParent));

            this.drawingView.Invalidate();

            AsyncTcpServer.Initialize(IPAddress.Any, PORT);
            AsyncTcpServer.Instance.Start();

            CaptureService.Initialize(new ScreenCapture(this.Window.DecorView.RootView), 1000);
            CaptureService.Instance.ScreenCaptured += (sender, args) =>
            {
                AsyncTcpServer.Instance.Write(JsonConvert.SerializeObject(args.Value));
            };
            CaptureService.Instance.Start();
        }
Ejemplo n.º 2
0
 public FrmMain()
 {
     log = flf.CreateLogger();
     try
     {
         InitializeComponent();
         dic = new ProcessControVariables().SetKeyValue();
         LogFactory.Assign(new ConsoleLogFactory());
         // 异步通讯初始化 端口10001 编码UTF8
         server          = new AsyncTcpServer(10001);
         server.Encoding = Encoding.UTF8;
         // 客户端连接事件
         server.ClientConnected +=
             new EventHandler <TcpClientConnectedEventArgs>(server_ClientConnected);
         // 客户端断开事件
         server.ClientDisconnected +=
             new EventHandler <TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
         // 接受string类型电文事件
         server.PlaintextReceived +=
             new EventHandler <TcpDatagramReceivedEventArgs <string> >(server_PlaintextReceived);
         // 接受byte[]类型电文事件
         server.DatagramReceived     += new EventHandler <TcpDatagramReceivedEventArgs <byte[]> >(server_DatagramReceived);
         frmMM.ManualOperationOrders += FrmMM_ManualOperationOrders;
         // 启动服务程序
         server.Start();
     }
     catch (Exception ex) { log.Exception(ex); }
 }
Ejemplo n.º 3
0
    void Awake()
    {
        Application.runInBackground = true;
        DontDestroyOnLoad(this);

        prot = new SimpleProtocolFilter();
        rpc  = new RPCParser();
        rpc.addRpcMethod("Add", Add);
        rpc.addRpcMethod("Screenshot", Screenshot);
        rpc.addRpcMethod("GetScreenSize", GetScreenSize);
        rpc.addRpcMethod("Dump", Dump);
        rpc.addRpcMethod("GetDebugProfilingData", GetDebugProfilingData);
        rpc.addRpcMethod("SetText", SetText);
        rpc.addRpcMethod("GetSDKVersion", GetSDKVersion);

        mRunning = true;

        server                  = new AsyncTcpServer(port);
        server.Encoding         = Encoding.UTF8;
        server.ClientConnected +=
            new EventHandler <TcpClientConnectedEventArgs> (server_ClientConnected);
        server.ClientDisconnected +=
            new EventHandler <TcpClientDisconnectedEventArgs> (server_ClientDisconnected);
        server.DatagramReceived +=
            new EventHandler <TcpDatagramReceivedEventArgs <byte[]> > (server_Received);
        server.Start();
        Debug.Log("Tcp server started");
    }
Ejemplo n.º 4
0
 public TcpServerLogger(RichTextBox rtbLog, RequestInfo request, AsyncTcpServer tcpServer, TcpClient tcpClient) : base(false)
 {
     this.rtbLog    = rtbLog;
     this.request   = request;
     this.tcpServer = tcpServer;
     this.tcpClient = tcpClient;
 }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            UIApplication.SharedApplication.IdleTimerDisabled = true;

            // Perform any additional setup after loading the view, typically from a nib.
            AsyncTcpServer.Initialize(IPAddress.Any, PORT);
            AsyncTcpServer.Instance.Start();

            CaptureService.Initialize(new ScreenCapture(), 1000);
            CaptureService.Instance.ScreenCaptured += (sender, args) =>
            {
                AsyncTcpServer.Instance.Write(JsonConvert.SerializeObject(args.Value));
            };
            CaptureService.Instance.Start();
            lblHelloWorld.Text = (IosExtensions.GetIPAddress() ?? IPAddress.Any).ToString();

            drawingView = new DrawingView();
            drawingView.BackgroundColor = UIColor.Clear;
            drawingView.Frame           = new RectangleF(0, 0, 1024, 768);
            drawingView.Bounds          = new RectangleF(0, 0, 1024, 768);

            this.View.AddSubview(drawingView);
        }
Ejemplo n.º 6
0
 public void CloseServer()
 {
     if (server != null && isTcpStart)
     {
         server.SendAll(NetworkCommand.EXIT);
         server.DataReceived -= Server_DataReceived;
         server.Dispose();
         heartBeat.Abort();
         checkHeartBeat.Abort();
         isTcpStart = false;
         server     = null;
     }
     clientDic.Clear();
     if (studentDic.Count > 0)
     {
         List <string> itemList = new List <string>(studentDic.Keys);
         foreach (var item in itemList)
         {
             studentDic[item].Destory();
             studentDic.Remove(item);
         }
     }
     studentDic.Clear();
     closeBroadcaster();
 }
Ejemplo n.º 7
0
    // Use this for initialization
    void Start()
    {
        asyncServer = new AsyncTcpServer(IPAddress.Any, 11999);
        asyncServer.MessageReceived  += HandleMessageReceived;
        asyncServer.DisConnectClient += HandlerDisConnect;

        asyncServer.Start();
    }
Ejemplo n.º 8
0
        public MJpegStreamingServer(int listenPort, string boundary)
        {
            Port     = listenPort;
            Boundary = boundary;

            _server          = new AsyncTcpServer(Port);
            _server.Encoding = Encoding.ASCII;
            _clients         = new ConcurrentDictionary <string, TcpClient>();
        }
Ejemplo n.º 9
0
 public void Start(int port)
 {
     server                      = new AsyncTcpServer(port);
     server.Encoding             = Encoding.UTF8;
     server.OnClientConnected    = MT_OnClientConnected;
     server.OnClientDisconnected = MT_OnClientDisconnected;
     server.OnDatagramReceived   = MT_OnDatagramReceived;
     server.Start();
 }
Ejemplo n.º 10
0
 private ServiceCore()
 {
     Console.Write("监听服务初始化");
     server                     = new AsyncTcpServer(TCP_SERVER_PORT);
     server.Encoding            = System.Text.Encoding.UTF8;
     server.ClientConnected    += server_Connected;
     server.ClientDisconnected += server_Disconnected;
     server.DatagramReceived   += server_DatagramReceived;
     Console.WriteLine(" -> 完成.");
 }
Ejemplo n.º 11
0
    void Awake()
    {
        Application.runInBackground = true;
        DontDestroyOnLoad(this);
        prot = new SimpleProtocolFilter();
        rpc  = new RPCParser();
        rpc.addRpcMethod("isVRSupported", vr_support.isVRSupported);
        rpc.addRpcMethod("hasMovementFinished", vr_support.IsQueueEmpty);
        rpc.addRpcMethod("RotateObject", vr_support.RotateObject);
        rpc.addRpcMethod("ObjectLookAt", vr_support.ObjectLookAt);
        rpc.addRpcMethod("Screenshot", Screenshot);
        rpc.addRpcMethod("GetScreenSize", GetScreenSize);
        rpc.addRpcMethod("Dump", Dump);
        rpc.addRpcMethod("GetDebugProfilingData", GetDebugProfilingData);
        rpc.addRpcMethod("SetText", SetText);

        rpc.addRpcMethod("GetSDKVersion", GetSDKVersion);

        mRunning = true;

        for (int i = 0; i < 5; i++)
        {
            this.server                  = new AsyncTcpServer(port + i);
            this.server.Encoding         = Encoding.UTF8;
            this.server.ClientConnected +=
                new EventHandler <TcpClientConnectedEventArgs>(server_ClientConnected);
            this.server.ClientDisconnected +=
                new EventHandler <TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
            this.server.DatagramReceived +=
                new EventHandler <TcpDatagramReceivedEventArgs <byte[]> >(server_Received);
            try
            {
                this.server.Start();
                Debug.Log(string.Format("Tcp server started and listening at {0}", server.Port));
                break;
            }
            catch (SocketException e)
            {
                Debug.Log(string.Format("Tcp server bind to port {0} Failed!", server.Port));
                Debug.Log("--- Failed Trace Begin ---");
                Debug.LogError(e);
                Debug.Log("--- Failed Trace End ---");
                // try next available port
                this.server = null;
            }
        }
        if (this.server == null)
        {
            Debug.LogError(string.Format("Unable to find an unused port from {0} to {1}", port, port + 5));
        }
        vr_support.ClearCommands();
    }
Ejemplo n.º 12
0
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="port">端口号</param>
 public void Init(int port)
 {
     try
     {
         server = new AsyncTcpServer(new IPEndPoint(IPAddress.Any, port), null, new EDCodecBuilder());
         server.OnSessionDataReceived += Server_OnSessionDataReceived;
         server.OnSessionStarted      += Server_OnSessionStarted;
         server.OnSessionClosed       += Server_OnSessionClosed;
         server.Listener();
         Console.WriteLine("服务端已启动!");
     }
     catch (Exception ex)
     {
         LogHelper.WriteError(ex);
     }
 }
Ejemplo n.º 13
0
 void StartServer()
 {
     if (!isTcpStart)
     {
         LogTool.Log(ipAddress + ":" + tcpPort);
         if (tcpServer == null)
         {
             tcpServer = new AsyncTcpServer(IPAddress.Parse(ipAddress), tcpPort);
             tcpServer.maxConnectCount = maxCount;
             tcpServer.Start();
             tcpServer.DataReceived += Server_DataReceived;
             heartBeat      = Loom.StartSingleThread(HeartBeat, System.Threading.ThreadPriority.AboveNormal, true);
             checkHeartBeat = Loom.StartSingleThread(CheckHeatBeat, System.Threading.ThreadPriority.Normal, true);
         }
         isTcpStart = true;
     }
 }
Ejemplo n.º 14
0
        public MainProcess()
        {
            RootPath = Environment.CurrentDirectory;
            _context = SynchronizationContext.Current;
            string msg = $"System start ";

            Logger(msg);
            server                  = new AsyncTcpServer(9999);
            server.Encoding         = Encoding.UTF8;
            server.ClientConnected +=
                new EventHandler <TcpClientConnectedEventArgs>(server_ClientConnected);
            server.ClientDisconnected +=
                new EventHandler <TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
            server.PlaintextReceived +=
                new EventHandler <TcpDatagramReceivedEventArgs <string> >(server_PlaintextReceived);
            server.Start();
            Logger("Server listening");
            #region Gocator Initi
            gocator.DeviceStatusEvent   += Gocator_DeviceStatusEvent;
            gocator.OnDataReceivedEvent += Gocator_OnDataReceivedEvent;
            gocator.InitialAcq();
            #endregion
            #region UI Binding
            Run               = new RelayCommand(RunExcute, RunCanExcute);
            Stop              = new RelayCommand(StopExcute, StopCanExcute);
            LineEditor01      = new RelayCommand(LineEditor01Excute, LineEditor01CanExcute);
            LineEditor02      = new RelayCommand(LineEditor02Excute, LineEditor02CanExcute);
            LineEditor03      = new RelayCommand(LineEditor03Excute, LineEditor03CanExcute);
            Match             = new RelayCommand(MatchExcute, MatchCanExcute);
            Debug             = new RelayCommand(DebugExcute, DebugCanExcute);
            ImageSourceTop    = new BitmapImage(new Uri(ConfigPath.LogoPath));
            ImageSourceBottom = new BitmapImage(new Uri(ConfigPath.LogoPath));
            #endregion
            #region AVL RunTime
            try
            {
                string avsProjectPath = ConfigPath.AVProgramPath;
                macros = SinvoProgramMacrofilters.Create(avsProjectPath);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            #endregion
        }
Ejemplo n.º 15
0
 /// <summary>
 /// 服务器启动,核心部分
 /// </summary>
 void startserver()
 {
     ClientList.ctPrint += ShowLog;
     try
     {
         ALLOffLine();
         server                     = new AsyncTcpServer(2758);//-----端口号改成: 2758-----
         server.Encoding            = Encoding.ASCII;
         server.ClientConnected    += new EventHandler <TcpClientConnectedEventArgs>(server_ClientConnected);
         server.ClientDisconnected += new EventHandler <TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
         server.DatagramReceived   += new EventHandler <TcpDatagramReceivedEventArgs <byte[]> >(server_DatagramReceived);
         server.Start();
     }
     catch (Exception)
     {
         txtLog.Text += "服务器启动失败";
     }
 }
Ejemplo n.º 16
0
        static void Main(string[] args)
        {
            LogFactory.Assign(new ConsoleLogFactory());

            server                     = new AsyncTcpServer(9999);
            server.Encoding            = Encoding.UTF8;
            server.ClientConnected    += new EventHandler <TcpClientConnectedEventArgs>(server_ClientConnected);
            server.ClientDisconnected += new EventHandler <TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
            server.PlaintextReceived  += new EventHandler <TcpDatagramReceivedEventArgs <string> >(server_PlaintextReceived);
            server.Start();

            Console.WriteLine("TCP server has been started.");
            Console.WriteLine("Type something to send to client...");
            while (true)
            {
                string text = Console.ReadLine();
                server.SendToAll(text);
            }
        }
Ejemplo n.º 17
0
 /// <summary>
 /// 服务端初始化
 /// </summary>
 public void ServerInit()
 {
     try
     {
         if (isLive)
         {
             return;
         }
         IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11368);
         tcpServer = new AsyncTcpServer(iPEndPoint, new ServerMessage(), new AlgorithmBuilder());
         tcpServer.Listener();
         Console.WriteLine("服务端已启动");
         isLive = true;
     }
     catch (Exception ex)
     {
         Console.WriteLine($"服务端启动失败:{ex.ToString()}");
     }
 }
Ejemplo n.º 18
0
//        private static string[] GetIpAddresses()
//        {
//            return Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).Select(x => x.ToString()).ToArray();
//        }

        public static void Main(string[] args)
        {
            AsyncTcpServer.Initialize(IPAddress.Any, PORT);
            AsyncTcpServer.Instance.DataReceived += (sender, e) => System.Console.WriteLine("Received data from client {0}, data: {1}", e.Value1.Client.LocalEndPoint.ToString(), e.Value2);
            AsyncTcpServer.Instance.Start();

            CaptureService.Initialize(new ScreenCapture(), 1000);
            CaptureService.Instance.ScreenCaptured += (sender, e) =>
            {
                var jsonString = "{" + string.Format("\"CursorX\":0,\"CursorY\":0,\"EncodedBitmap\":\"{0}\"", e.Value.EncodedBitmap) + "}";
                AsyncTcpServer.Instance.Write(jsonString);
            };
            CaptureService.Instance.Start();


            System.Console.WriteLine("Listening for incoming connections...");
            System.Console.ReadLine();

            CaptureService.Instance.Stop();
        }
 public MessageReceiverEx(AsyncTcpServer asyncTcpServer)
 {
     _asyncTcpServer = asyncTcpServer;
     MessageReceived = Observable.FromEventPattern<MessageReceivedEventArgs>(_asyncTcpServer, "MessageReceived");
     Random rnd = new Random();
     LogEvents =
         Observable.Create<string>(
             o =>
                 {
                     return 
                     MessageReceived.Subscribe(
                         data =>
                             {
                                 string value = Encoding.UTF8.GetString(data.EventArgs.Message.MessageData);
                                 Console.WriteLine("Received "+value + " at "+ Thread.CurrentThread.ManagedThreadId);
                                 o.OnNext(value);
                             });
                });
     
 }
Ejemplo n.º 20
0
        public MessageReceiverEx(AsyncTcpServer asyncTcpServer)
        {
            _asyncTcpServer = asyncTcpServer;
            MessageReceived = Observable.FromEventPattern <MessageReceivedEventArgs>(_asyncTcpServer, "MessageReceived");
            Random rnd = new Random();

            LogEvents =
                Observable.Create <string>(
                    o =>
            {
                return
                (MessageReceived.Subscribe(
                     data =>
                {
                    string value = Encoding.UTF8.GetString(data.EventArgs.Message.MessageData);
                    Console.WriteLine("Received " + value + " at " + Thread.CurrentThread.ManagedThreadId);
                    o.OnNext(value);
                }));
            });
        }
Ejemplo n.º 21
0
        private static List <TcpClient[]> battleList = new List <TcpClient[]>();                         //对战列表

        static void Main(string[] args)
        {
            server          = new AsyncTcpServer(8088);
            server.Encoding = Encoding.UTF8;
            //注册事件
            server.ClientConnected +=
                new EventHandler <TcpClientConnectedEventArgs>(server_ClientConnected);
            server.ClientDisconnected +=
                new EventHandler <TcpClientDisconnectedEventArgs>(server_ClientDisconnected);
            server.DatagramReceived +=
                new EventHandler <TcpDatagramReceivedEventArgs <byte[]> >(server_DatagramReceived);
            server.Start();
            Console.WriteLine("TCP server has been started.");
            Console.WriteLine("Type something to send to client...");
            while (true)
            {
                string text = Console.ReadLine();
                server.SendAll(text);
            }
        }
Ejemplo n.º 22
0
    void Awake()
    {
        Application.runInBackground = true;
        DontDestroyOnLoad(this);

        prot = new SimpleProtocolFilter();
        rpc  = new RPCParser();
        rpc.addRpcMethod("Add", Add);
        rpc.addRpcMethod("Screenshot", Screenshot);
        rpc.addRpcMethod("GetScreenSize", GetScreenSize);
        rpc.addRpcMethod("Dump", Dump);
        rpc.addRpcMethod("GetDebugProfilingData", GetDebugProfilingData);
        rpc.addRpcMethod("SetText", SetText);
        rpc.addRpcMethod("GetSDKVersion", GetSDKVersion);

        mRunning = true;

        for (int i = 0; i < 5; i++)
        {
            this.server                  = new AsyncTcpServer(port + i);
            this.server.Encoding         = Encoding.UTF8;
            this.server.ClientConnected +=
                new EventHandler <TcpClientConnectedEventArgs> (server_ClientConnected);
            this.server.ClientDisconnected +=
                new EventHandler <TcpClientDisconnectedEventArgs> (server_ClientDisconnected);
            this.server.DatagramReceived +=
                new EventHandler <TcpDatagramReceivedEventArgs <byte[]> > (server_Received);
            try {
                this.server.Start();
                Debug.Log(string.Format("Tcp server started and listening at {0}", server.Port));
                break;
            } catch (SocketException e) {
                // try next available port
                this.server = null;
            }
        }
        if (!this.server)
        {
            Debug.LogError(string.Format("Unable to find an unused port from {0} to {1}", port, port + 5));
        }
    }
Ejemplo n.º 23
0
        private void BtnStart_Click(object sender, EventArgs e)
        {
            try
            {
                if (tcpServer == null)
                {
                    tcpServer                     = new AsyncTcpServer(ConfigHelper.AppSettings <int>("ServerPort"));
                    tcpServer.Encoding            = Encoding.UTF8;
                    tcpServer.ClientConnected    += TcpServer_ClientConnected;
                    tcpServer.ClientDisconnected += TcpServer_ClientDisconnected;
                    tcpServer.DatagramReceived   += TcpServer_DatagramReceived;
                }

                tcpServer.Start();
                context.Logger.WriteLog("服务已启动!");
                SetButtonEnabled(true);
            }
            catch (Exception ex)
            {
                context.Logger.WriteLog("服务启动失败:" + ex.ToString());
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 开始监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void StartMonitorClicked(object sender, RoutedEventArgs e)
        {
            //初始化Tcp服务器
            if (tcpServer == null)
            {
                tcpServer = new AsyncTcpServer(IPAddress.Any, 6666);
                tcpServer.ClientConnected    += tcpServer_ClientConnected;
                tcpServer.ClientDisconnected += tcpServer_ClientDisconnected;
            }
            //开始监控
            tcpServer.Start();

            //开始监控线程,定时向客户端发送服务状态
            if (monitorThread == null)
            {
                monitorThread = new Thread(SendServiceInfos);
                monitorThread.IsBackground = true;
                monitorThread.Start();
            }

            lblStatus.Content = "监控中...";
        }
Ejemplo n.º 25
0
        /// <summary>
        /// 服务器启动关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (server.IsRunning)
            {
                try
                {
                    server.Stop();
                    lock (CurrentClient)
                    {
                        CurrentClient.Clear();
                    }
                    label1.BeginInvoke(new EventHandler(delegate
                    {
                        label1.Text = "0";
                    }));
                    btnStart.Text = "启动服务";
                }
                catch (Exception ex) { }
            }
            else
            {
                try
                {
                    server                     = new AsyncTcpServer(2758);
                    server.Encoding            = Encoding.ASCII;
                    server.ClientConnected    += new EventHandler <TcpClientConnectedEventArgs>(server_ClientConnected);
                    server.ClientDisconnected += new EventHandler <TcpClientDisconnectedEventArgs>(server_ClientDisconnected);

                    server.DatagramReceived += new EventHandler <TcpDatagramReceivedEventArgs <byte[]> >(server_DatagramReceived);
                    server.Start(2049);
                    btnStart.Text = "停止服务";
                }
                catch (Exception ex)
                {
                    LogHelper.showLog(txtLog, "服务器启动失败" + ex.Message);
                }
            }
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            AsyncTcpServer.Initialize(IPAddress.Any, PORT);
            AsyncTcpServer.Instance.DataReceived += (sender, e) => System.Console.WriteLine("Received data from client {0}, data: {1}", e.Value1.Client.LocalEndPoint.ToString(), e.Value2);
            AsyncTcpServer.Instance.Start();

            ScreenCapturer.Instance.ScreenCaptured += (sender, e) =>
            {
                string jsonString = null;

                e.Value.Created = DateTime.Now;

                Stopwatch.Measure("JsonParse", () => { jsonString = JsonConvert.SerializeObject(e.Value); });
                Stopwatch.Measure("TcpSend", () => { AsyncTcpServer.Instance.Write(jsonString); });
            };
            ScreenCapturer.Instance.Start();

            System.Console.WriteLine("Listening for incoming connections on ip addresses {0}, port {1}. press any key to terminate the app..", string.Join(", ", GetIpAddresses()), PORT);
            System.Console.ReadLine();

            ScreenCapturer.Instance.Stop();
            //AsyncTcpServer.Instance.Stop();
        }
Ejemplo n.º 27
0
        public SocketHelper(string name, string port, string restCode, string UnitNum)
        {
            R_Keeper_CodeCard = string.Empty;
            Name = name;
            Port = port;
            R_Keeper_RestCode         = restCode;
            R_Keeper_UnitNum          = UnitNum;
            asyncTcpServer            = new AsyncTcpServer();
            asyncTcpServer.OnMessage += OnEventMessageServer;
            SocketHelper.CheckNo      = 1;
            context = SynchronizationContext.Current;
            GetVendingID(name);

            if (VendingID > 0)
            {
                context.Post(new SendOrPostCallback(MessageCallBack), (object)string.Format("Connect to db {0}.\n", name));
            }
            //AppendLog("Connect to db.\n");
            else
            {
                context.Post(new SendOrPostCallback(MessageCallBack), (object)string.Format("Connect to db {0}.\n", name));
            }
            //AppendLog("No Connect to db.\n");
        }
Ejemplo n.º 28
0
 public static bool Load()
 {
     Server = CommonSerializer.LoadObjFormBinaryFile <AsyncTcpServer>($@"D:\FastAutomation\Server.xml", out bool bLoadOK, out Exception ex);
     return(bLoadOK);
 }
Ejemplo n.º 29
0
        public async Task ServerIsAbleToProcessPacketsAndCleansUpResources(ISocketSessionFactory sessionFactory, IProcessor processor, IPlayer player)
        {
            player.GetCityCount().Returns(1);
            player.HasTwoFactorAuthenticated = DateTime.Now;

            var socketAwaitablePool = new SocketAwaitablePool(10);
            var buffer = new BlockingBufferManager(1000, 15);

            Socket             serverSideSocket = null;
            AsyncSocketSession session          = null;

            sessionFactory.CreateAsyncSocketSession(Arg.Any <string>(), Arg.Any <Socket>())
            .Returns(args =>
            {
                serverSideSocket = args.Arg <Socket>();
                session          = new AsyncSocketSession(string.Empty, serverSideSocket, processor, socketAwaitablePool, buffer)
                {
                    Player = player
                };
                return(session);
            });

            AsyncTcpServer server = new AsyncTcpServer(sessionFactory, socketAwaitablePool, buffer);

            try
            {
                server.Start("127.0.0.1", 0);

                // Connect and verify client connected and socket options are set
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
                {
                    NoDelay = true
                };

                var packetToSend1 = new Packet(Command.MarketSell);
                packetToSend1.AddString("Hello");
                var bytesToSendOnConnect = packetToSend1.GetBytes();

                await socket.ConnectAsync(new SocketAwaitable
                {
                    RemoteEndPoint = server.LocalEndPoint
                });

                await Task.Delay(1000);

                await socket.SendAsync(new SocketAwaitable
                {
                    Buffer = new ArraySegment <byte>(bytesToSendOnConnect, 0, bytesToSendOnConnect.Length)
                });

                await Task.Delay(1000);

                server.GetSessionCount().Should().Be(1);
                serverSideSocket.Connected.Should().BeTrue();
                serverSideSocket.NoDelay.Should().BeTrue();
                serverSideSocket.SendTimeout.Should().Be(1000);

                // Send packets and verify server processes packets
                var packetToSend2 = new Packet(Command.MarketBuy);
                packetToSend2.AddString("World");
                var bytesToSecondAfterConnect = packetToSend2.GetBytes();
                await socket.SendAsync(new SocketAwaitable
                {
                    Buffer = new ArraySegment <byte>(bytesToSecondAfterConnect, 0, bytesToSecondAfterConnect.Length)
                });

                await Task.Delay(1000);

                // Stop server and verify it disconnect and releases resources
                server.Stop();

                await Task.Delay(1000);

                player.HasTwoFactorAuthenticated.Should().Be(null);

                serverSideSocket.Connected.Should().BeFalse();
                socketAwaitablePool.Count.Should().Be(10);
                buffer.AvailableBuffers.Should().Be(15);

                processor.Received(1).Execute(session, Arg.Is <Packet>(packet => packet.GetBytes().SequenceEqual(bytesToSecondAfterConnect)));
                processor.Received(1).Execute(session, Arg.Is <Packet>(packet => packet.GetBytes().SequenceEqual(bytesToSendOnConnect)));
                processor.Received(1).ExecuteEvent(session, Arg.Is <Packet>(packet => packet.Cmd == Command.OnDisconnect));
            }
            finally
            {
                server.Stop();
            }
        }
Ejemplo n.º 30
0
 public MessageReceiver(AsyncTcpServer asyncTcpServer)
 {
     _asyncTcpServer = asyncTcpServer;
     _asyncTcpServer.MessageReceived += srv_MessageReceived;
     _eventSubject = new Subject <LogEventArgs>();
 }
Ejemplo n.º 31
0
        private void Form1_Load(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine("ABC");

            server = new AsyncTcpServer(IPAddress.Parse("127.0.0.1"), 9999);
            server.Encoding = Encoding.UTF8;
            server.ClientConnected += server_ClientConnected;
            server.ClientDisconnected += server_ClientDisconnected;
            server.DatagramReceived += server_DatagramReceived;
            server.Start();
        }
Ejemplo n.º 32
0
        private void GetRound(AsyncTcpServer asyncTcpServer, byte[] array)
        {
            try
            {
                string sendMessage = string.Empty;
                byte[] data        = null;

                string msg = CryptoVending.Decrypt(array);
                context.Post(new SendOrPostCallback(MessageCallBack), (object)(msg + "\n"));
                //AppendLog(msg + "\n");

                Logbook.FileAppend("AccountID: " + AccountID.ToString() + " " + msg, EventType.Info);

                string[] message = msg.Split(';');



                VendingCommands vendingCommands = (VendingCommands)Convert.ToInt16(message[0]);
                switch (vendingCommands)
                {
                case VendingCommands.GetBalance:

                    R_Keeper_CodeCard    = HexToDec(HexToDescSort(message[2]));
                    R_Keeper_BalanceCard = getBalance(SocketHelper.R_Keeper_CodeCard);
                    R_Keeper_BonusCard   = RKeeper.RKeeper.AccountInfo.Bonus == 1;

                    msg = string.Format("Code Card {0} -> Balance {1} Bonus Enable {2} ", R_Keeper_CodeCard, R_Keeper_BalanceCard, R_Keeper_BonusCard);
                    context.Post(new SendOrPostCallback(MessageCallBack), (object)(msg + "\n"));

                    sendMessage = string.Format("5;0;{0};", R_Keeper_BalanceCard);

                    Logbook.FileAppend("AccountID: " + AccountID.ToString() + " " + sendMessage, EventType.Info);

                    data = GetMessageToByte(sendMessage);

                    if (asyncTcpServer.GetCouuntClient() > 0)
                    {
                        asyncTcpServer.SendMessage(asyncTcpServer.GetTcpClient(0), data);
                    }

                    break;

                case VendingCommands.BeginTran:
                    ID          = random.Next(1, 1000);
                    sendMessage = string.Format("1;0;{0}", ID);

                    Logbook.FileAppend("AccountID: " + AccountID.ToString() + " " + sendMessage, EventType.Info);

                    data = GetMessageToByte(sendMessage);
                    asyncTcpServer.SendMessage(asyncTcpServer.GetTcpClient(0), data);
                    break;

                case VendingCommands.BuyWares:
                    WaresPrice  = Convert.ToInt32(message[4]);
                    sendMessage = "2;0;";

                    Logbook.FileAppend("AccountID: " + AccountID.ToString() + " " + sendMessage, EventType.Info);

                    data = GetMessageToByte(sendMessage);
                    asyncTcpServer.SendMessage(asyncTcpServer.GetTcpClient(0), data);
                    break;

                case VendingCommands.SuccsesBuy:
                    if (AccountID > 0)
                    {
                        Logbook.FileAppend(string.Format("AccountID: {0} R_Keeper_CodeCard: {1} R_Keeper_BalanceCard: {2} WaresPrice: {3} WaresName: {4} ", AccountID, R_Keeper_CodeCard, R_Keeper_BalanceCard, WaresPrice, WaresName), EventType.Info);

                        if (IsSaveDB)
                        {
                            PutWaresSale(R_Keeper_CodeCard, R_Keeper_BalanceCard, WaresPrice, WaresName);
                        }

                        if (RKeeperWaresSale(AccountID, WaresPrice))
                        {
                            msg = string.Format("Code Card {0} -> Append Wares Sale {1} ", R_Keeper_CodeCard, WaresPrice);
                            context.Post(new SendOrPostCallback(MessageCallBack), (object)(msg + "\n"));

                            Logbook.FileAppend(string.Format("Success AccountID: {0} R_Keeper_CodeCard: {1} R_Keeper_BalanceCard: {2} WaresPrice: {3} WaresName: {4} ", AccountID, R_Keeper_CodeCard, R_Keeper_BalanceCard, WaresPrice, WaresName), EventType.Info);
                            if (R_Keeper_BonusCard)
                            {
                                AppendBonus = 0;
                                if (RKeeperAppnedBonus(AccountID, WaresPrice, R_Keeper_BonusTotal, ref AppendBonus))
                                {
                                    msg = string.Format("Code Card {0} -> Append Bonus {1} ", R_Keeper_CodeCard, AppendBonus);
                                    context.Post(new SendOrPostCallback(MessageCallBack), (object)(msg + "\n"));
                                    Logbook.FileAppend(string.Format("Success AccountID: {0} R_Keeper_CodeCard: {1} R_Keeper_BalanceCard: {2} Bonus: {3} ", AccountID, R_Keeper_CodeCard, R_Keeper_BalanceCard, AppendBonus), EventType.Info);
                                }
                                else
                                {
                                    Logbook.FileAppend(string.Format("Unsuccess AccountID: {0} R_Keeper_CodeCard: {1} R_Keeper_BalanceCard: {2} Bonus: {3} ", AccountID, R_Keeper_CodeCard, R_Keeper_BalanceCard, AppendBonus), EventType.Info);
                                }
                            }
                        }
                        else
                        {
                            Logbook.FileAppend(string.Format("UnSuccessfull AccountID: {0} R_Keeper_CodeCard: {1} R_Keeper_BalanceCard: {2} WaresPrice: {3} WaresName: {4} ", AccountID, R_Keeper_CodeCard, R_Keeper_BalanceCard, WaresPrice, WaresName), EventType.Info);
                        }
                    }

                    sendMessage = "3;0;";

                    Logbook.FileAppend("AccountID: " + AccountID.ToString() + " " + sendMessage, EventType.Info);

                    data = GetMessageToByte(sendMessage);
                    asyncTcpServer.SendMessage(asyncTcpServer.GetTcpClient(0), data);
                    AccountID = 0;

                    break;

                case VendingCommands.CancelBuy:
                    sendMessage = string.Format("4;{0}", ID);

                    Logbook.FileAppend(sendMessage, EventType.Info);

                    data = GetMessageToByte(sendMessage);
                    asyncTcpServer.SendMessage(asyncTcpServer.GetTcpClient(0), data);
                    break;

                default:
                    //asyncTcpServer.SendMessage(asyncTcpServer.GetTcpClient(0), message[0] + ";3");
                    break;
                }
            }
            catch (Exception e)
            {
                context.Post(new SendOrPostCallback(MessageCallBack), (object)(e.Message + "\n"));
                // MessageBox.Show(e.Message);
            }
        }
Ejemplo n.º 33
0
        static void Main(string[] args)
        {
            AsyncTcpServer srv = new AsyncTcpServer(new IPEndPoint(IPAddress.Any, 50001));
            srv.Start();
            MessageReceiver receiver = new MessageReceiver(srv);
            MovingWindowSequence seq = new MovingWindowSequence(1000*60, 1000*5*60);
            string mongoUrl = File.ReadAllText("settings\\mongoConnection");
            //CountersDatabase.InitConnection(mongoUrl);
            var observableEvents = receiver.ObservableEvents.Buffer(seq.BufferOpenings, seq.ClosingWindowSequenceSelector).Publish();
            //observableEvents.Connect();
            Settings settings = new Settings();
            settings.ObservableEvents = observableEvents;
            settings.ReadAggregators();
            CountersAutoDiscoverer countersAutoDiscoverer = new CountersAutoDiscoverer(receiver.ObservableEvents, settings);
            countersAutoDiscoverer.StartDiscovery();
            
            CounterDumper counterDumper = new CounterDumper(receiver.ObservableEvents);
            CounterForwarder counterForwarder = new CounterForwarder(receiver.ObservableEvents);

            DeadCountersDetector deadCountersDetector = new DeadCountersDetector(receiver.ObservableEvents, settings);
            
            observableEvents.Subscribe(l => Console.WriteLine("Total events: " + l.Count));
            ConsoleKeyInfo keyInfo;
            while ((keyInfo = Console.ReadKey()).Key !=ConsoleKey.Enter)
            {
                if (keyInfo.Key == ConsoleKey.Add)
                {
                    seq.IncreaseInterval(1000);
                    Console.WriteLine("Interval is {0} ms now", seq.MoveEvery);
                }
                if (keyInfo.Key == ConsoleKey.Subtract)
                {
                    seq.DecreaseInterval(1000);
                    Console.WriteLine("Interval is {0} ms now", seq.MoveEvery);
                }
                if (keyInfo.Key == ConsoleKey.R)
                {
                    settings.ReadAggregators();
                    Console.WriteLine("Aggregators were updated");
                }

                if (keyInfo.Key == ConsoleKey.F)
                {
                    if (counterForwarder.IsForwarding)
                    {
                        counterForwarder.StopForwarding();
                        Console.WriteLine("Forwarding stopped");
                    }
                    else
                    {
                        counterForwarder.StartForwarding();
                        Console.WriteLine("Forwarding started");
                    }
                }
                if (keyInfo.Key == ConsoleKey.D)
                {
                    if (counterDumper.IsDumping)
                    {
                        counterDumper.StopDumping();
                        Console.WriteLine("Counter Dumping Stopped");
                    }
                    else
                    {
                        counterDumper.StartDumping();
                        Console.WriteLine("Counter Dumping Started");
                    }
                }
                if (keyInfo.Key == ConsoleKey.A)
                {
                    File.WriteAllText("deadCounters",deadCountersDetector.GetCounterFreshnessTimeStats());
                    Console.WriteLine("Stats have been written to file deadCounters");
                }
            }
        }
 public MessageReceiver(AsyncTcpServer asyncTcpServer)
 {
     _asyncTcpServer = asyncTcpServer;
     _asyncTcpServer.MessageReceived += srv_MessageReceived;
     _eventSubject = new Subject<LogEventArgs>();
 }
Ejemplo n.º 35
0
 /// <inheritdoc />
 public void OnCreatedConnection(AsyncTcpServer aAsyncTcpServer, ClientConnection aClientConnection)
 {
     // Создаем новый экземпляр сессии.
     var session = CreateSession(aClientConnection);
     lock (sessions) {
         sessions.Add(session);
     }
     if (callback != null) {
         callback.OnCreatedSession(this, session);
     }
     Logger.Info("Создана новая сессия.");
 }
Ejemplo n.º 36
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public bool StartServer(string ip,int port)
        {
            __server = new AsyncTcpServer(System.Net.IPAddress.Parse(ip), port);
            __server.PlaintextReceived += __server_PlaintextReceived;
            __server.Start();

            return true;
        }