Esempio n. 1
0
 public void Send(byte[] buffer)
 {
     if (IsConnection)
     {
         _clientSocket.Send(buffer, 0, buffer.Length);
     }
     else
     {
         throw new SocketException(1000);
     }
 }
Esempio n. 2
0
 public void SendHeadbeat()
 {
     Task.Factory.StartNew(() =>
     {
         while (true)
         {
             bool isStart = true;
             while (isStart)
             {
                 if (m_wsQClient != null && m_wsQClient.IsConnected)
                 {
                     var m          = new object();
                     byte[] request = SerHelper.Serialize(m);
                     _logger.LogInformation($"[SendHeadbeat] 发送心跳");
                     m_wsQClient.Send(request);
                 }
                 else
                 {
                     isStart = false;
                     break;
                 }
                 Thread.Sleep(20 * 1000);//休眠20秒
             }
         }
     });
 }
Esempio n. 3
0
        private void WSClient__Opened(object sender, EventArgs e)
        {
            if (m_wsQClient.IsConnected && ((AsyncTcpSession)sender).LocalEndPoint == m_wsQClient?.LocalEndPoint)
            {
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        if (m_wsQClient != null && m_wsQClient.IsConnected)
                        {
                            OMDC_HeartBeatReq HB = new OMDC_HeartBeatReq();
                            HB.head.PktSize      = BitConverter.GetBytes((UInt16)40);
                            HB.head.MsgCount[0]  = 1;
                            HB.head.Filter[0]    = 0;
                            HB.head.SeqNum       = BitConverter.GetBytes(num);
                            HB.head.SendTime     = BitConverter.GetBytes(GETTick() * 100);
                            HB.msgType.MsgSize   = BitConverter.GetBytes((UInt16)24);
                            HB.msgType.MsgType   = BitConverter.GetBytes((UInt16)1000);
                            byte[] request       = SerHelper.Serialize(HB);

                            m_wsQClient.Send(request);
                            Console.WriteLine($"heartbeat_{num}:{ByteConvertUtil.byteToHexStr(request)}");
                        }
                        num++;
                        Thread.Sleep(1500);
                    }
                });
            }
        }
Esempio n. 4
0
        internal IFuture Send(object data, ushort type,
                              ushort subType = 0, bool zip = false, bool encrypted = false)
        {
            if (_session == null || !_session.IsOpened)
            {
                Start();

                lock (_rootSync)
                {
                    int count = 0;
                    while (!_session.IsOpened && count < 10)
                    {
                        Thread.Sleep(1000);
                        count++;
                    }
                }
            }

            if (_session.IsOpened)
            {
                return(_session.Send(new DefaultMessage(data, type, subType, zip, encrypted)));
            }

            return(null);
        }
Esempio n. 5
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);
            }
        }
        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. 7
0
        private void SendDataThread()
        {
            try
            {
                while (true)
                {
                    if (!GlobalDataInterface.CommportConnectFlag)
                    {
                        Thread.Sleep(10);
                        continue;
                    }
                    if (GlobalDataInterface.SendMsgData.Count == 0)
                    {
                        Thread.Sleep(10);
                        continue;
                    }
                    byte[] bytes;
                    if (GlobalDataInterface.SendMsgData.TryDequeue(out bytes))
                    {
                        tcpClient.Send(bytes, 0, bytes.Length);
                    }
                    Thread.Sleep(10);
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("ProjectSetForm中函数SendDataThread出错" + ex);
#if REALEASE
                GlobalDataInterface.WriteErrorInfo("ProjectSetForm中函数SendDataThread出错" + ex);
#endif
            }
        }
Esempio n. 8
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. 9
0
        /// <summary>
        /// 向服务器发送命令行协议数据(此函数会将数据以Base64[UTF-8]方式编码,在服务器读取后,需要解码使用)
        /// </summary>
        /// <param name="cmd">请求的命令 </param>
        /// <param name="msg">数据</param>
        private void SendCmd(CMD cmd, MsgInfo msg)
        {
            msg.FromUser = tName.Text;
            var frames = msg.ToFrame(cmd.ToString().Length + 1);

            foreach (var frame in frames)
            {
                var byteData = string.Format(CMD_FORMAT, cmd, frame).ToBin();
                client.Send(byteData, 0, byteData.Length);
            }
        }
Esempio n. 10
0
        public void A_TestAsyncTcpSession()
        {
            AppServer appServer = new AppServer();

            Assert.IsTrue(appServer.Setup("127.0.0.1", 50060));

            Assert.IsTrue(appServer.Start());

            appServer.NewRequestReceived += (s, e) =>
            {
                Assert.AreEqual("Hello!", e.Key);
                byte[] bytesToSend = Encoding.UTF8.GetBytes("Welcome!");
                s.Send(bytesToSend, 0, bytesToSend.Length);
            };

            AsyncTcpSession asyncTcpSession = new AsyncTcpSession();

            asyncTcpSession.ReceiveBufferSize = 8;

            AutoResetEvent sessionDataReceivedEvent = new AutoResetEvent(false);

            asyncTcpSession.DataReceived += (s, e) =>
            {
                string message = Encoding.ASCII.GetString(e.Data);

                Assert.AreEqual("Welcome!", message);

                sessionDataReceivedEvent.Set();
            };

            AutoResetEvent connectedEvent = new AutoResetEvent(false);

            asyncTcpSession.Connected += (s, e) =>
            {
                connectedEvent.Set();
            };

            asyncTcpSession.Connect(serverEndpoint);

            Assert.IsTrue(connectedEvent.WaitOne(timeout));

            Assert.IsTrue(asyncTcpSession.IsConnected);

            byte[] data = (Encoding.ASCII.GetBytes("Hello!" + Environment.NewLine));

            asyncTcpSession.Send(data, 0, data.Length);

            sessionDataReceivedEvent.WaitOne(timeout);

            asyncTcpSession.Close();

            appServer.Stop();
        }
        public void Send(MessageType messageType, byte[] data)
        {
            var header = BitConverter.GetBytes((int)messageType);

            using (var stream = new MemoryStream(header.Length + sizeof(int) + data.Length))
            {
                stream.Write(header, 0, header.Length);
                stream.Write(BitConverter.GetBytes(data.Length), 0, sizeof(int));
                stream.Write(data, 0, data.Length);
                stream.Seek(0, SeekOrigin.Begin);
                _asyncTcpSession.Send(stream.GetBuffer(), 0, (int)stream.Length);
            }
        }
Esempio n. 12
0
 private void SendData(byte[] dataBytes)
 {
     if (dataBytes != null && dataBytes.Length > 0)
     {
         if (socketStatus == SocketStatus.Ready)
         {
             tcpSession.Send(dataBytes, 0, dataBytes.Length);
         }
     }
     else
     {
         Debugger.Log("tcp send msg is null");
     }
 }
Esempio n. 13
0
        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="strData">十六进制字符串</param>
        /// <returns>是否发送成功</returns>
        public static bool SendData(string strData)
        {
            if (string.IsNullOrEmpty(strData))
            {
                return(false);
            }
            byte[] bytes = strToToHexByte(strData);

            try
            {
                tcpClient.Send(bytes, 0, bytes.Length);
                return(true);
            }
            catch
            {
                //socketSend.Shutdown(SocketShutdown.Both);
                //socketSend.Close();
                //if (Connect())
                //{
                //    return SendData(strData);
                //}
            }
            return(false);
        }
Esempio n. 14
0
        private static void tcpSession_Connected(object sender, EventArgs e)
        {
            AsyncTcpSession session = sender as AsyncTcpSession;

            Console.WriteLine("tcpSession_Connected");

            var buffer = new CGD.buffer(50);

            buffer.append <int>(123);
            buffer.append <short>(0);
            buffer.append <string>("전송한 데이터");
            buffer.set_front <short>(buffer.Count, 4);

            session.Send(buffer);
        }
Esempio n. 15
0
    public static void sendMessage(AsyncTcpSession client, BasePacket packet)
    {
//		using (MemoryStream sendStream = new MemoryStream()) {
//			CodedOutputStream os = CodedOutputStream.CreateInstance(sendStream);
//          WriteMessageNoTag equivalent to WriteVarint32, WriteByte (byte [])
//          that is: variable length message header + message body
//			os.WriteMessageNoTag(request);
//			os.WriteRawBytes(bytes);
//			os.Flush();

        MemoryStream sendStream = new MemoryStream();

        packet.WriteTo(sendStream);
        byte[] bytes = sendStream.ToArray();
        client.Send(new ArraySegment <byte>(bytes));
//		}
    }
Esempio n. 16
0
 /// <summary>
 /// 向服务器发命令行协议的数据
 /// </summary>
 /// <param name="key">命令名称</param>
 /// <param name="data">数据</param>
 public void SendCommand(string key, string data)
 {
     if (client.IsConnected)
     {
         string str = string.Format("{0} {1}\r\n", key, data);
         LogSingleton.LogHelper.Info("Send-" + str);
         byte[] arr = Encoding.Default.GetBytes(str);
         client.Send(arr, 0, arr.Length);
         // Console.WriteLine($"发送消息:{str}");
     }
     else
     {
         //  throw new InvalidOperationException("未建立连接");
         LogSingleton.LogHelper.Info("Send-未建立连接");
         Console.WriteLine("未建立连接");
     }
 }
Esempio n. 17
0
    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="cmd">消息ID</param>
    /// <param name="data">消息内容</param>
    public void SendCmd(Const.CMD cmd, byte[] data)
    {
        var lenArray = BitConverter.GetBytes(data.Length + 2);
        var cmdArray = BitConverter.GetBytes((int)cmd);

        byte[] head     = new byte[] { lenArray[0], lenArray[1], cmdArray[0], cmdArray[1] };
        var    sendData = new byte[6 + data.Length];//6=包头(4)+包尾(2)

        //包头
        Buffer.BlockCopy(head, 0, sendData, 0, 4);
        //包体
        Buffer.BlockCopy(data, 0, sendData, 4 * sizeof(byte), data.Length);
        //包尾
        byte[] tail = new byte[] { 0x0, 0x0 };
        Buffer.BlockCopy(tail, 0, sendData, (4 + data.Length) * sizeof(byte), 2);

        client.Send(sendData, 0, sendData.Length);
    }
Esempio n. 18
0
        //public Queue<CDBStatusModel> status = new Queue<CDBStatusModel>();

        /**
         * 这里 C# 的实现和Protobuf 官方给的Java实现是一样的
         */
        public void sendMessage(AsyncTcpSession client, LaidianCommandModel request)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                CodedOutputStream os = CodedOutputStream.CreateInstance(stream);
                //一定要去看它的代码实现,
                os.WriteMessageNoTag(request);

                /**
                 * WriteMessageNoTag 等价于 WriteVarint32, WriteByte(byte[])
                 * 也就是:变长消息头 + 消息体
                 */
                os.Flush();

                byte[] data = stream.ToArray();
                client.Send(new ArraySegment <byte>(data));
            }
        }
Esempio n. 19
0
        /// <summary>
        /// 通过 socket 发送数据
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool pushMessage(JObject message)
        {
            try
            {
                if (!_appClient.IsConnected)
                {
                    _appClient.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
                }

                byte[] data = Encoding.Default.GetBytes(message.ToString());
                _appClient.Send(data, 0, data.Length);
            }
            catch (Exception ex)
            {
                nlogger.Error("error with the socket client: " + ex.Message);
                return(false);
            }

            return(true);
        }
Esempio n. 20
0
 public static void SendMsg(string message)
 {
     if (tcpClient != null && tcpClient.IsConnected)
     {
         try
         {
             #region 发送字符串
             byte[] data = Encoding.UTF8.GetBytes(message);
             tcpClient.Send(data, 0, data.Length);
             #endregion
         }
         catch (Exception)
         {
             throw;
         }
     }
     else
     {
         log.Error("YunHost网关客户端连接未启动,发送失败!" + message);
         Console.WriteLine("YunHost网关客户端连接未启动,发送失败!" + message);
     }
 }
Esempio n. 21
0
        private 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);

            int    bufferLength = (int)buffer.extract_uint();
            ushort bufferType   = (ushort)buffer.extract_byte();

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

            case 2:
                ping = (int)pingStopwatch.ElapsedMilliseconds;
                pingStopwatch.Reset();
                break;
            }
        }
Esempio n. 22
0
 private void sendHello()
 {
     ClientSession.Send(sendData, 0, sendData.Length);
 }
Esempio n. 23
0
        public static void Send(this AsyncTcpSession session, string message)
        {
            var messageBytes = Encoding.UTF8.GetBytes(message.EndsWith("\r\n") ? message : message + "\r\n");

            session.Send(messageBytes, 0, messageBytes.Length);
        }
 public void SendString(string text)
 {
     byte[] buffer = Encoding.UTF8.GetBytes("C " + text + "##");
     BaseClient.Send(buffer, 0, buffer.Length);
 }
 public void SendString(string text)
 {
     byte[] buffer = Encoding.UTF8.GetBytes("S " + text + "#BordercaseServerLog#");
     BaseClient.Send(buffer, 0, buffer.Length);
 }
Esempio n. 26
0
        private void button_ClientSend_Click(object sender, EventArgs e)
        {
            string strSend = textBox_ClientSend.Text;

            client.Send(System.Text.Encoding.ASCII.GetBytes(strSend), 0, strSend.Length);
        }