private static void tcpSession_DataReceived(object sender, DataEventArgs e)
        {
            AsyncTcpSession session = sender as AsyncTcpSession;

            byte[] tmpBuffer = e.Data;
            var    buffer    = new CGD.buffer(e.Data, 0, e.Length);

            ushort bufferLength = buffer.extract_ushort();
            ushort bufferType   = buffer.extract_byte();

            length += bufferLength;
            count++;

            Console.SetCursorPosition(22, 0);
            Console.Write(count);
            Console.SetCursorPosition(22, 1);
            Console.Write(length);

            switch (bufferType)
            {
            case 1:
                pingStopwatch.Start();
                session.Send(NcsTemplateBuffer.HeartbeatBuffer1);
                break;

            case 2:
                Console.SetCursorPosition(7, 3);
                pingStopwatch.Stop();
                Console.SetCursorPosition(7, 3);
                Console.Write(pingStopwatch.ElapsedMilliseconds + "              ");
                Debug.WriteLine(pingStopwatch.ElapsedMilliseconds);
                pingStopwatch.Reset();
                break;
            }
        }
Esempio n. 2
0
        private void bConnect_Click(object sender, EventArgs e)
        {
            if (bConnect.Text == "Disconnect")
            {
                if (client != null)
                {
                    client.Close();
                    client = null;
                }

                bConnect.Text = "Connect";
                return;
            }

            try
            {
                client = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse(tServer.Text), Convert.ToInt32(tPort.Value)));
                #region // bind events
                client.Closed       += client_Closed;
                client.Connected    += client_Connected;
                client.DataReceived += client_DataReceived;
                client.Error        += client_Error;
                #endregion
                AppendNotify("Connecting...");
                bConnect.Text = "Disconnect";
                client.Connect();
            }
            catch (Exception ex)
            {
                AppendNotify("Connect failed: " + ex.Message);
            }
        }
Esempio n. 3
0
 private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
 {
     log.Debug("断线重连计时器中……");
     if (tcpClient != null)
     {
         if (tcpClient.IsConnected)
         {
             cl_timer.Stop();
             cl_timer.Enabled = false;
             cl_timer.Dispose();
             Heartbeat();
             log.Debug("连接RYZig断线重连成功!!开始心跳!!");
         }
         else
         {
             tcpClient = null;
             ConnectServer();
         }
     }
     else
     {
         log.Debug("连接RYZig断线重连失败!!");
         ConnectServer();
     }
 }
Esempio n. 4
0
 private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
 {
     //Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
     //Task.Run(() =>
     //{
     if (tcpClient != null)
     {
         if (tcpClient.IsConnected)
         {
             cl_timer.Stop();
             cl_timer.Enabled = false;
             cl_timer.Dispose();
             Heartbeat();
             log.Info("连接YunHost断线重连成功!!开始心跳!!");
         }
         else
         {
             tcpClient = null;
             ConnectServer();
         }
     }
     else
     {
         ConnectServer();
         log.Error("连接YunHost断线重连失败!!");
     }
     //});
 }
Esempio n. 5
0
        private static void tcpSession_Closed(object sender, EventArgs e)
        {
            AsyncTcpSession session = sender as AsyncTcpSession;

            _tcpSession.Remove(session);
            Interlocked.Decrement(ref connectCount);
        }
Esempio n. 6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            if (!server.Setup(8888))
            {
                return;
            }
            if (!server.Start())
            {
                return;
            }
            server.NewSessionConnected += Server_NewSessionConnected;
            server.SessionClosed       += Server_SessionClosed;
            server.NewRequestReceived  += Server_NewRequestReceived;
            MyShowInfoDelgete           = new ShowInfo((str, add) =>
            {
                if (add)
                {
                    listBox1.Items.Add(str);
                }
                else
                {
                    listBox1.Items.Remove(str);
                }
            });
            ShowClientRecv = new ShowInfo((str, add) =>
            {
                textBox_ClientRecv.Text = str;
            });

            client = new AsyncTcpSession();
            client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
            client.DataReceived += Client_DataReceived;
            client.NoDelay       = true;
        }
Esempio n. 7
0
        public void Init(string host, int port, int index, bool littleEnd)
        {
            try
            {
                //if (inited)
                if (tcpSession != null)
                {
                    tcpSession.Close();
                    tcpSession = null;
                }

                //if (!inited)
                {
                    adapter = new NetAdapter();
                    adapter.SetEndianness(littleEnd);
                    netClientId  = index;
                    socketStatus = SocketStatus.NotConnet;
                    currentHost  = host;
                    currentPort  = port;
                    IPAddress  ipEndPoint = IPAddress.Parse(currentHost);
                    IPEndPoint ipEnd      = new IPEndPoint(ipEndPoint, currentPort);
                    tcpSession               = new AsyncTcpSession(ipEnd);
                    tcpSession.Connected    += onConnected;
                    tcpSession.Closed       += onClosed;
                    tcpSession.Error        += onError;
                    tcpSession.DataReceived += OnDataReceive;
                }
            }
            catch (System.Exception e)
            {
                Debugger.LogError("net client init exception->" + host + "^" + port + "^" + index + "^" + littleEnd + "^" + e.ToString());
            }

            inited = true;
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            tcpSession = new AsyncTcpSession();

            tcpSession.Connected    += tcpSession_Connected;
            tcpSession.Closed       += tcpSession_Closed;
            tcpSession.DataReceived += tcpSession_DataReceived;
            tcpSession.Error        += tcpSession_Error;
            tcpSession.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000));
            var tmpData = "";

            while (tmpData != "q")
            {
                tmpData = Console.ReadLine();

                var buffer = new CGD.buffer(50);

                buffer.append <int>(123);
                buffer.append <short>(0);
                buffer.append <string>(tmpData);
                buffer.set_front <short>(buffer.Count, 4);

                tcpSession.Send(buffer);
            }
        }
Esempio n. 9
0
        void OpenClinet(AsyncTcpSession tcpClient, int id)
        {
            AppendInfo(string.Concat("TcpClient:", id.ToString(), ", 开始连接服务器!"));
            AsyncFuture openFuture = tcpClient.Open() as AsyncFuture;

            openFuture.FutureCompleted += OpenFutureCompleted;
        }
Esempio n. 10
0
        internal IFuture Start()
        {
            lock (_rootSync)
            {
                if (_session != null && (_session.IsOpened ||
                                         _session.SessionState == SessionState.Opening))
                {
                    return(null);
                }

                if (_session != null)
                {
                    _session.Close();
                    _session = null;
                }

                if (_session == null)
                {
                    _session = new AsyncTcpSession(_remoteEP, true, 5000, 10000, true);
                    _session.PacketEncoder    = new DefaultPacketEncoder(_messageBodyEncoder);
                    _session.PacketDecoder    = new DefaultPacketDecoder(_messageBodyDecoder);
                    _session.ObjectReceived  += SessionObjectReceived;
                    _session.ExceptionCaught += SessionExceptionCaught;
                    _session.StateChanged    += SessionStateChanged;
                    _session.Closed          += SessionClosed;
                }

                return(_session.Open());
            }
        }
Esempio n. 11
0
    void OnGUI()
    {
        if (GUI.Button(new Rect(100, 130, 100, 25), "SuperSocket"))
        {
            buffer.Data = new byte[8192];
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(host), port);

            AsyncTcpSession client = new AsyncTcpSession(endPoint);
            client.Connected    += OnConnected;
            client.DataReceived += OnDataReceive;

            client.Connect();

            NamePacket.Builder b = new NamePacket.Builder();
            b.SetName("Client name data");
            NamePacket np = b.BuildPartial();

            MemoryStream stream = new MemoryStream();
            np.WriteTo(stream);
            byte[] bytes = stream.ToArray();

            BasePacket.Builder basePacketBuilder = new BasePacket.Builder();
            basePacketBuilder.SetPacketId(64553060);
            basePacketBuilder.SetPacketData(
                ByteString.CopyFrom(bytes)
                );

            BasePacket basePacket = basePacketBuilder.BuildPartial();

            sendMessage(client, basePacket);

            print("SuperSocket!");
        }
    }
Esempio n. 12
0
        static void Main(string[] args)
        {
            ServiceContainer.AddAndStartService(new ServiceInfo {
                Name = "DemoService", Factory = () => new DemoService()
            });
            //            ServiceContainer.AddAndStartService(new ServiceInfo { Name = "DemoService2",Factory = () => new DemoService2() });
            ServiceProxy.CreateService <IDemoService>().Test(new TestCommand {
                Name = "sam", Password = "******"
            });
            Console.ReadLine();
            return;

            if (Console.ReadKey().KeyChar == 'd')
            {
                var serviceName = "DemoService";
                var actionName  = "Test";
                var parameters  = JsonConvert.SerializeObject(new TestCommand
                {
                    Name     = "test",
                    Password = "******"
                });
                var message = $"{serviceName}/{actionName}/{parameters}";
                var session = new AsyncTcpSession();
                var service = ServiceContainer.Services.First(a => a.Name == serviceName).GetInstance();
                session.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), service.Communicator.Port));
                session.Connected    += Connected;
                session.Error        += Error;
                session.DataReceived += DataReceived;
                session.Closed       += Closed;
                while (!session.IsConnected)
                {
                    Task.Delay(TimeSpan.FromMilliseconds(10)).GetAwaiter().GetResult();
                }
                session.Send(message);
                //                    .ForEach(service =>
                //                {
                //
                //                    session.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), service.GetInstance().Communicator.Port));
                //                    session.Connected += Connected;
                //                    session.Error += Error;
                //                    session.DataReceived += DataReceived;
                //                    session.Closed += Closed;
                //                });
                //                var client = new EasyClient();
                //                client.Initialize(new Test(), req=>
                //                {
                //                    Console.WriteLine(req.Body);
                //                });
                //                ServiceContainer.Services.ForEach(service =>
                //                {
                //
                //                    if (client.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), service.GetInstance().Communicator.Port)).Result)
                //                    {
                //                        client.Send(Encoding.UTF8.GetBytes("cccccccccccccccc\r\n"));
                //                    }
                //                });
                Console.ReadLine();
            }
        }
Esempio n. 13
0
 private void FormMain_Load(object sender, EventArgs e)
 {
     tcpSession               = new AsyncTcpSession();
     tcpSession.Connected    += tcpSession_Connected;
     tcpSession.Closed       += tcpSession_Closed;
     tcpSession.DataReceived += tcpSession_DataReceived;
     tcpSession.Error        += tcpSession_Error;
 }
Esempio n. 14
0
 public static void ConnectServer()
 {
     tcpClient = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse("192.168.88.58"), 9004));
     tcpClient.DataReceived += TcpClient_DataReceived;
     tcpClient.Error        += TcpClient_Error;
     tcpClient.Closed       += TcpClient_Closed;
     tcpClient.Connect();
 }
Esempio n. 15
0
        void CreateClients()
        {
            int count = int.Parse(tbConnectCount.Text);

            IPEndPoint localEP = null;

            if (!string.IsNullOrEmpty(tbLocalIp.Text))
            {
                localEP = new IPEndPoint(IPAddress.Parse(tbLocalIp.Text), 0);
            }

            IPEndPoint remoteEP = new IPEndPoint(
                IPAddress.Parse(tbServerIp.Text), int.Parse(tbPort.Text));

            BeginInvoke((Action)(() =>
            {
                AsyncTcpSession tcpClient;
                lvSession.BeginUpdate();

                for (int i = 0; i < count; i++)
                {
                    try
                    {
                        tcpClient = new AsyncTcpSession(localEP, remoteEP, true, 5000, 1000, true);
                        tcpClient.PacketEncoder = new DefaultPacketEncoder(obj => Encoding.UTF8.GetBytes(obj.ToString()));
                        tcpClient.PacketDecoder = new DefaultPacketDecoder((buffer, startIndex, length, type) =>
                                                                           Encoding.UTF8.GetString(buffer.ByteArray, startIndex, length));
                        tcpClient.Closed += TcpClient_Closed;
                        tcpClient.ObjectSent += TcpClient_ObjectSent;
                        tcpClient.StateChanged += TcpClient_StateChanged;
                        tcpClient.ObjectReceived += TcpClient_ObjectReceived;
                        tcpClient.ExceptionCaught += TcpClient_ExceptionCaught;

                        _connectCount++;
                        _tcpClients.Add(tcpClient, new SessionInfo
                        {
                            Id = _connectCount
                        });

                        lvSession.Items.Add(new ListViewItem(new string[] {
                            _connectCount.ToString(), "", "0", "0", ""
                        })
                        {
                            Name = _connectCount.ToString(),
                            Tag = tcpClient
                        });
                    }
                    catch (Exception ex)
                    {
                        AppendInfo("创建 TcpClient 失败:" + ex.ToString());
                    }
                }

                lvSession.EndUpdate();
                OpenClients();
            }));
        }
Esempio n. 16
0
        void SendData(AsyncTcpSession tcpClient)
        {
            IPacket packet = new DefaultPacket(_sendPacket.Buffer.Duplicate(), _sendPacket.EndPoint);

            tcpClient.Flush(packet);
            //future.FutureCompleted += (sender, e) =>
            //{
            //    //SendData();
            //};
        }
Esempio n. 17
0
 public static void ConnectServer()
 {
     tcpClient = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 50000));//47.95.247.135,,192.168.1.104//192.168.82.107
     tcpClient.DataReceived += TcpClient_DataReceived;
     //tcpClient.Error += TcpClient_Error;
     tcpClient.Closed += TcpClient_Closed;
     tcpClient.Connect();
     log.Debug("RYZig网关客户端连接中……");
     Console.WriteLine("RYZig网关客户端连接中……");
 }
Esempio n. 18
0
        void SessionClosed(object sender, SessionEventArgs e)
        {
            _session.ObjectReceived  -= SessionObjectReceived;
            _session.ExceptionCaught -= SessionExceptionCaught;
            _session.Closed          -= SessionClosed;
            _session = null;

            Global.Resolve <ILoggerFactory>()
            .GetCurrentClassLogger()
            .Info("Session Closed: {0}", e.Session);
        }
Esempio n. 19
0
 public void LogOffSocketEvent(AsyncTcpSession clientSocket)
 {
     if (clientSocket == null)
     {
         return;
     }
     clientSocket.Closed       -= _clientSocket_Closed;
     clientSocket.DataReceived -= _clientSocket_DataReceived;
     clientSocket.Connected    -= _clientSocket_Connected;
     clientSocket.Error        -= _clientSocket_Error;
 }
Esempio n. 20
0
 void CloseClient(AsyncTcpSession tcpClient)
 {
     try
     {
         tcpClient.Close();
     }
     catch (Exception ex)
     {
         AppendInfo("Close Client: " + ex.ToString());
     }
 }
Esempio n. 21
0
 internal void Close()
 {
     lock (_rootSync)
     {
         if (_session != null && _session.SessionState != SessionState.Closed)
         {
             _session.Close();
             _session = null;
         }
     }
 }
Esempio n. 22
0
 /// <summary>
 /// 关闭连接
 /// </summary>
 public void Close()
 {
     if (client != null)
     {
         if (client.IsConnected)
         {
             client.Close();
             client = null;
         }
     }
 }
Esempio n. 23
0
 private void RegistrationSocketEvent(AsyncTcpSession clientSocket)
 {
     if (clientSocket == null)
     {
         return;
     }
     clientSocket.Closed       += _clientSocket_Closed;
     clientSocket.DataReceived += _clientSocket_DataReceived;
     clientSocket.Connected    += _clientSocket_Connected;
     clientSocket.Error        += _clientSocket_Error;
 }
Esempio n. 24
0
 /// <summary>
 /// 建立连接
 /// </summary>
 public void Start(string _ip, int _port)
 {
     ip                   = _ip;
     port                 = _port;
     client               = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse(ip), port));
     client.Connected    += Connected;
     client.DataReceived += DataReceived;
     client.Error        += Error;
     client.Closed       += Closed;
     client.Connect();
 }
Esempio n. 25
0
 /// <summary>
 /// 连接断开事件
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void Closed(object sender, EventArgs e)
 {
     Debug.Log("Closed()");
     if (client != null)
     {
         if (client.IsConnected)
         {
             client.Close();
         }
         client = null;
     }
 }
Esempio n. 26
0
        public NcsMain(Form1 form)
        {
            NcsTemplateBuffer.SetTempBuffer();

            tcpSession = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse("192.168.0.17"), 65535));

            tcpSession.Connected    += tcpSession_Connected;
            tcpSession.Closed       += tcpSession_Closed;
            tcpSession.DataReceived += tcpSession_DataReceived;
            tcpSession.Error        += new EventHandler <ErrorEventArgs>(tcpSession_Error);
            tcpSession.Connect();
        }
Esempio n. 27
0
        public NcsMain(string ip, int port, Form1 form)
        {
            NcsTemplateBuffer.SetTempBuffer();

            tcpSession = new AsyncTcpSession(new IPEndPoint(IPAddress.Parse(ip), port));

            tcpSession.Connected    += tcpSession_Connected;
            tcpSession.Closed       += tcpSession_Closed;
            tcpSession.DataReceived += tcpSession_DataReceived;
            tcpSession.Error        += new EventHandler <ErrorEventArgs>(tcpSession_Error);
            tcpSession.Connect();
        }
Esempio n. 28
0
        public NcsMain(IPEndPoint ipEndPoint, Form1 form)
        {
            NcsTemplateBuffer.SetTempBuffer();

            tcpSession = new AsyncTcpSession(ipEndPoint);

            tcpSession.Connected    += tcpSession_Connected;
            tcpSession.Closed       += tcpSession_Closed;
            tcpSession.DataReceived += tcpSession_DataReceived;
            tcpSession.Error        += new EventHandler <ErrorEventArgs>(tcpSession_Error);
            tcpSession.Connect();
        }
Esempio n. 29
0
        private AsyncTcpSession WSClient_ReConnect()
        {
            var wsClient = new AsyncTcpSession();

            wsClient.Connected        += new EventHandler(WSClient__Opened);
            wsClient.Closed           += new EventHandler(WSClient__Closed);
            wsClient.Error            += new EventHandler <SuperSocket.ClientEngine.ErrorEventArgs>(WSClient__Error);
            wsClient.DataReceived     += new EventHandler <SuperSocket.ClientEngine.DataEventArgs>(WSClient_DataReceived);
            wsClient.ReceiveBufferSize = 1024 * 64;
            wsClient.Connect(ipp);
            return(wsClient);
        }
Esempio n. 30
0
 private void MainWindow_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (client == null)
     {
         return;
     }
     if (client.IsConnected)
     {
         client.Close();
     }
     client = null;
 }