Example #1
0
        public async Task TestConnectRepeat()
        {
            var client = new EasyClient();

            client.Initialize(new FakeReceiveFilter(), (p) =>
            {
                // do nothing
            });

            Console.WriteLine("Connecting");
            var ret = await client.ConnectAsync(new DnsEndPoint("github.com", 443));

            Console.WriteLine("Connected");
            Assert.True(ret);

            Console.WriteLine("Closing");
            await client.Close();

            Console.WriteLine("Closed");

            Console.WriteLine("Connecting");
            ret = await client.ConnectAsync(new DnsEndPoint("github.com", 443));

            Console.WriteLine("Connected");

            Assert.True(ret);

            Console.WriteLine("Closing");
            await client.Close();

            Console.WriteLine("Closed");
        }
Example #2
0
 public override void Close()
 {
     if (client.IsConnected)
     {
         client.Close();
     }
 }
 public async Task TestConnectRepeat()
 {
     var client = new EasyClient();
     
     client.Initialize(new FakeReceiveFilter(), (p) =>
     {
         // do nothing
     });
     
     Console.WriteLine("Connecting");
     var ret = await client.ConnectAsync(new DnsEndPoint("github.com", 443));
     Console.WriteLine("Connected");
     Assert.True(ret);
     
     Console.WriteLine("Closing");
     await client.Close();
     Console.WriteLine("Closed");
     
     Console.WriteLine("Connecting");
     ret = await client.ConnectAsync(new DnsEndPoint("github.com", 443));
     Console.WriteLine("Connected");
     
     Assert.True(ret);
     
     Console.WriteLine("Closing");
     await client.Close();
     Console.WriteLine("Closed");
 }
Example #4
0
 public void Close()
 {
     if (client != null)
     {
         client.Close();
         StopTimer();
     }
 }
Example #5
0
        public async Task C_AppServerEasyClientNewSessionConnected()
        {
            AppServer appServer = new AppServer();

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

            Assert.IsTrue(appServer.Start());

            AutoResetEvent sessionConnectedEvent = new AutoResetEvent(false);

            appServer.NewSessionConnected += (s) =>
            {
                sessionConnectedEvent.Set();
            };

            EasyClient easyClient = new EasyClient();

            AutoResetEvent helloReceivedEvent = new AutoResetEvent(false);

            easyClient.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (p) =>
            {
                //do nothing
            });

            bool connected = await easyClient.ConnectAsync(serverEndpoint);

            Assert.IsTrue(connected);

            sessionConnectedEvent.WaitOne(timeout);

            await easyClient.Close();

            appServer.Stop();
        }
Example #6
0
        public async Task D_AppServerSendsWelcomeOnEasyClientNewSessionConnected()
        {
            AppServer appServer = new AppServer();

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

            Assert.IsTrue(appServer.Start());

            AutoResetEvent welcomeReceiveEvent = new AutoResetEvent(false);

            appServer.NewSessionConnected += (s) =>
            {
                s.Send("Welcome!");
            };

            EasyClient easyClient = new EasyClient();

            easyClient.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (p) =>
            {
                Assert.AreEqual("Welcome!", p.Key);
                welcomeReceiveEvent.Set();
            });

            bool x = easyClient.ConnectAsync(serverEndpoint).Result;

            welcomeReceiveEvent.WaitOne();

            await easyClient.Close();

            appServer.Stop();
        }
Example #7
0
 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (client != null && client.IsConnected)
     {
         client.Close();
     }
 }
 public void Close()
 {
     if (_tcpClient.IsConnected)
     {
         _tcpClient.Close();
     }
 }
Example #9
0
        public async Task C_ConnectEasyClientToHL7Interface()
        {
            HL7InterfaceBase hl7Interface = new HL7InterfaceBase();
            AutoResetEvent   newSessionConnectedSignal = new AutoResetEvent(false);
            AutoResetEvent   welcomMessageReceived     = new AutoResetEvent(false);

            Assert.IsTrue(hl7Interface.Initialize());

            Assert.IsTrue(hl7Interface.Start());

            hl7Interface.HL7Server.NewSessionConnected += (hl7Session) =>
            {
                Assert.That(hl7Session is HL7Session);
                Assert.That(hl7Session.Connected);
                newSessionConnectedSignal.Set();
            };

            EasyClient client = new EasyClient();

            client.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (packageInfo) =>
            {
                //nothing
            });

            Assert.IsTrue(client.ConnectAsync(endPointA).Result);

            Assert.That(client.IsConnected);

            Assert.That(newSessionConnectedSignal.WaitOne());

            await client.Close();

            hl7Interface.Stop();
        }
Example #10
0
 void OnApplicationQuit()
 {
     if (client.IsConnected)
     {
         client.Close();
     }
 }
Example #11
0
        public void Stop()
        {
            ///Sending tasks
            HL7Request item;

            while (m_OutgoingRequests.TryTake(out item))
            {
                if (!item.SenderTask.IsCompleted)
                {
                    item.RequestCancellationToken.Cancel();

                    item.RequestCompletedEvent.WaitOne();
                }
            }

            //Client
            if (!m_EasyClient.IsConnected)
            {
                //Connection
                m_ConnectionCancellationToken?.Cancel();
            }
            else
            {
                m_EasyClient.Close().Wait();
            }

            m_HL7Server.Stop();
        }
Example #12
0
 public void Close()
 {
     if (client != null)
     {
         client.Close();
     }
 }
Example #13
0
        public async Task G_AppServerWelcomeOnEasyClientNewSessionConnected()
        {
            AppServer appServer = new AppServer();

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

            Assert.IsTrue(appServer.Start());

            appServer.NewSessionConnected += (s) =>
            {
                s.Send("Welcome!");
            };

            EasyClient easyClient = new EasyClient();

            AutoResetEvent callbackEvent = new AutoResetEvent(false);

            easyClient.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (p) =>
            {
                callbackEvent.Set();
            });

            bool connected = await easyClient.ConnectAsync(serverEndpoint);

            Assert.IsTrue(connected);

            callbackEvent.WaitOne(timeout);

            await easyClient.Close();

            appServer.Stop();
        }
Example #14
0
 public void Disconnect()
 {
     if (this.IsConnected)
     {
         m_Client.Close();
     }
 }
Example #15
0
 public bool CloseConnect()
 {
     if (easyClient.IsConnected)
     {
         return(easyClient.Close().Result);
     }
     return(true);
 }
Example #16
0
 private void OnDestroy()
 {
     if (mClient != null)
     {
         mClient.Close();
         mClient = null;
     }
 }
Example #17
0
 private void TcpClose()
 {
     if (tcpClient != null)
     {
         tcpClient.Close();
         tcpClient = null;
     }
 }
Example #18
0
        public async Task M_EasyCLientSendsCommandToHL7InterfaceWaitAckAndResponse()
        {
            HL7InterfaceBase hl7Interface            = new HL7InterfaceBase();
            AutoResetEvent   ackReceived             = new AutoResetEvent(false);
            AutoResetEvent   commandResponseReceived = new AutoResetEvent(false);

            HL7Server serverSide = new HL7Server();

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

            Assert.IsTrue(hl7Interface.Initialize(serverSide, new HL7ProtocolBase(new HL7ProtocolConfig())));

            Assert.That(hl7Interface.Start());

            hl7Interface.NewRequestReceived += (s, e) =>
            {
                string response = MLLP.CreateMLLPMessage((new PrepareForSpecimenResponse()).Encode());

                byte[] dataToSend = Encoding.ASCII.GetBytes(response);

                s.Send(dataToSend, 0, dataToSend.Length);
            };

            PrepareForSpecimenRequest request = new PrepareForSpecimenRequest();

            EasyClient client = new EasyClient();

            client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) =>
            {
                if (packageInfo.Request.IsAcknowledge)
                {
                    Assert.That(packageInfo.Request is GeneralAcknowledgment);
                    Assert.That(HL7Parser.IsAckForRequest(request, packageInfo.Request));
                    ackReceived.Set();
                }
                else
                {
                    Assert.IsTrue(packageInfo.Request is PrepareForSpecimenResponse);
                    commandResponseReceived.Set();
                }
            });

            Assert.That(client.ConnectAsync(endPointA).Result);

            byte[] bytesToSend = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(request.Encode()));

            client.Send(bytesToSend);

            Assert.That(ackReceived.WaitOne());

            Assert.That(commandResponseReceived.WaitOne());

            await client.Close();

            serverSide.Stop();

            hl7Interface.Stop();
        }
Example #19
0
        public async Task I_AppServerAndEasyClientReceivesMultiblePackages()
        {
            var filterFactory = new DefaultReceiveFilterFactory <TestBeginEndMarkReceiveFilter, StringRequestInfo>();

            AppServer appServer = new AppServer(filterFactory);

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

            Assert.IsTrue(appServer.Start());

            int requestCount = 0;

            StringBuilder sb = new StringBuilder();

            appServer.NewRequestReceived += (s, e) =>
            {
                sb.Append(e.Key);

                if (++requestCount == 4)
                {
                    Assert.AreEqual("Can you serve me?", sb.ToString());
                    byte[] data = Encoding.ASCII.GetBytes("|Sure, ||" + "|how ||" + "|can ||" + "|I ||" + "|help?||");
                    requestCount = 0;
                    sb.Clear();

                    s.Send(data, 0, data.Length);
                }
            };

            EasyClient easyClient = new EasyClient();

            AutoResetEvent callbackEvent = new AutoResetEvent(false);

            StringBuilder sb1 = new StringBuilder(21);

            easyClient.Initialize(new TestProtoBaseBeginEndMarkReceiverFilter(), (p) =>
            {
                sb.Append(p.OriginalRequest);

                if (++requestCount == 5)
                {
                    Assert.AreEqual("Sure, how can I help?", sb.ToString());
                    callbackEvent.Set();
                }
            });

            bool connected = easyClient.ConnectAsync(serverEndpoint).Result;

            Assert.IsTrue(connected);

            easyClient.Send(Encoding.ASCII.GetBytes("#Can ##" + "#you ##" + "#serve ##" + "#me?##"));

            callbackEvent.WaitOne(timeout);

            await easyClient.Close();

            appServer.Stop();
        }
Example #20
0
        public void Close()
        {
            if (ticker != null)
            {
                ticker.Dispose();
            }

            if (client != null && client.IsConnected)
            {
                Logout();
                client.Close();
            }
        }
Example #21
0
        public async Task L_EasyClientSendsCommandToHL7InterfaceAndWaitAck()
        {
            HL7InterfaceBase hl7Interface            = new HL7InterfaceBase();
            AutoResetEvent   ackReceived             = new AutoResetEvent(false);
            AutoResetEvent   commandResponseReceived = new AutoResetEvent(false);

            HL7ProtocolBase protocol = new HL7ProtocolBase(new HL7ProtocolConfig()
            {
                IsAckRequired      = true,
                IsResponseRequired = true
            });

            HL7Server serverSide = new HL7Server();

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

            Assert.IsTrue(hl7Interface.Initialize(serverSide, protocol));

            Assert.That(hl7Interface.Start());

            PrepareForSpecimenRequest request = new PrepareForSpecimenRequest();

            EasyClient client = new EasyClient();

            client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) =>
            {
                if (packageInfo.Request.IsAcknowledge)
                {
                    Assert.That(packageInfo.Request is GeneralAcknowledgment);
                    Assert.That(HL7Parser.IsAckForRequest(request, packageInfo.Request));
                    ackReceived.Set();
                }
                else
                {
                    Assert.Fail();
                }
            });

            Assert.That(client.ConnectAsync(endPointA).Result);

            byte[] bytesToSend = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(request.Encode()));
            client.Send(bytesToSend);

            Assert.That(ackReceived.WaitOne(timeout));

            await client.Close();

            hl7Interface.Stop();
        }
Example #22
0
 /// <summary>
 /// 关闭
 /// </summary>
 public void Shutdown()
 {
     Logger.Debug($"客户端开始关闭");
     IsProcessRun = false;
     if (easyClient.IsConnected)
     {
         cts.Cancel();
     }
     else
     {
         easyClient.Close();
     }
     AckMessageQueue.Clear();
     Logger.Debug($"客户端结束关闭");
 }
Example #23
0
        public async Task B_EasyClientConnection()
        {
            EasyClient easyClient = new EasyClient();

            easyClient.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (p) =>
            {
                //do nothing
            });

            var ret = await easyClient.ConnectAsync(new DnsEndPoint("github.com", 443));

            Assert.True(ret);

            await easyClient.Close();
        }
Example #24
0
        public async Task E_EasyClientSendsHL7MessageToHL7InterfaceAndReceivesAck()
        {
            HL7InterfaceBase hl7Interface = new HL7InterfaceBase();

            AutoResetEvent newRequestReceived = new AutoResetEvent(false);

            Assert.IsTrue(hl7Interface.Initialize());

            Assert.IsTrue(hl7Interface.Start());

            PrepareForSpecimenRequest equipmentCommandRequest = new PrepareForSpecimenRequest();

            hl7Interface.HL7Server.NewRequestReceived += (hl7Session, hl7Request) =>
            {
                Assert.That(hl7Request is HL7Request);

                Assert.IsTrue(hl7Request.Request is PrepareForSpecimenRequest);

                Assert.That(hl7Session.Connected);
            };

            EasyClient client = new EasyClient();

            var tcs = new TaskCompletionSource <IHL7Message>();

            client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) =>
            {
                tcs.SetResult(packageInfo.Request);
            });

            Assert.That(await client.ConnectAsync(endPointA));

            byte[] data = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(equipmentCommandRequest.Encode()));

            client.Send(data);

            var result = await tcs.Task;

            Assert.IsTrue(result.IsAcknowledge);

            Assert.IsTrue(HL7Parser.IsAckForRequest(equipmentCommandRequest, result));

            await client.Close();

            hl7Interface.Stop();
        }
Example #25
0
        public async Task F_HL7InterfaceReceivesHL7MessageSendsAResponseToEasyClient()
        {
            HL7InterfaceBase hl7Interface = new HL7InterfaceBase();

            AutoResetEvent newRequestReceived = new AutoResetEvent(false);

            Assert.IsTrue(hl7Interface.Initialize());

            Assert.IsTrue(hl7Interface.Start());

            PrepareForSpecimenRequest equipmentCommandRequest = new PrepareForSpecimenRequest();

            hl7Interface.HL7Server.NewSessionConnected += (hl7Session) =>
            {
                Assert.That(hl7Session.Connected);

                string response = MLLP.CreateMLLPMessage((new PrepareForSpecimenResponse()).Encode());

                byte[] dataToSend = Encoding.ASCII.GetBytes(response);

                hl7Session.Send(dataToSend, 0, dataToSend.Length);
            };

            EasyClient client = new EasyClient();

            var tcs = new TaskCompletionSource <IHL7Message>();

            client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) =>
            {
                tcs.SetResult(packageInfo.Request);
            });

            Assert.That(await client.ConnectAsync(endPointA));

            var result = await tcs.Task;

            Assert.IsTrue(result is PrepareForSpecimenResponse);

            await client.Close();

            hl7Interface.Stop();
        }
Example #26
0
        static void Main()
        {
            // 实例化
            EasyClient easyClient = new EasyClient();

            // 连接成功触发事件
            easyClient.Connected += EasyClient_Connected;
            // 关闭成功触发事件
            easyClient.Closed += EasyClient_Closed;
            // 异常触发事件(连接失败,通讯异常)
            easyClient.Error += EasyClient_Error;
            // 设置过滤器
            // 设置消息处理程序
            easyClient.Initialize <MessagePackageInfo>(new MyReceiveFilter(), new Action <MessagePackageInfo>((l) => { Console.WriteLine(l); }));

            var task = easyClient.ConnectAsync(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2020));

            Console.ReadLine();
            easyClient.Close();
        }
Example #27
0
        public async Task J_EasyClientSendsCommandToHL7ServerAndWaitAck()
        {
            AutoResetEvent ackReceived = new AutoResetEvent(false);

            HL7Server hl7Server = new HL7Server();

            hl7Server.Setup("127.0.0.1", 50060);

            hl7Server.Start();

            PrepareForSpecimenRequest request = new PrepareForSpecimenRequest();

            EasyClient client = new EasyClient();

            client.Initialize(new ReceiverFilter(new HL7ProtocolBase()), (packageInfo) =>
            {
                if (packageInfo.Request.IsAcknowledge)
                {
                    Assert.That(packageInfo.Request is GeneralAcknowledgment);
                    Assert.That(HL7Parser.IsAckForRequest(request, packageInfo.Request));
                    ackReceived.Set();
                }
                else
                {
                    Assert.Fail();
                }
            });

            Assert.That(client.ConnectAsync(endPointA).Result);

            Assert.That(client.IsConnected);

            byte[] bytesToSend = Encoding.ASCII.GetBytes(MLLP.CreateMLLPMessage(request.Encode()));
            client.Send(bytesToSend);

            Assert.That(ackReceived.WaitOne());

            await client.Close();

            hl7Server.Stop();
        }
Example #28
0
        public async Task H_AppServerReceivesNewRequestBeginEndMarkReceiver()
        {
            var filterFactory = new DefaultReceiveFilterFactory <TestBeginEndMarkReceiveFilter, StringRequestInfo>();

            AppServer appServer = new AppServer(filterFactory);

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

            Assert.IsTrue(appServer.Start());

            appServer.NewRequestReceived += (s, e) =>
            {
                Assert.AreEqual("Hola!", e.Key);
                byte[] data = Encoding.ASCII.GetBytes("|" + "Howdy!" + "||");
                s.Send(data, 0, data.Length);
            };

            EasyClient easyClient = new EasyClient();

            AutoResetEvent callbackEvent = new AutoResetEvent(false);

            easyClient.Initialize(new TestProtoBaseBeginEndMarkReceiverFilter(), (p) =>
            {
                Assert.AreEqual("Howdy!", p.OriginalRequest);
                callbackEvent.Set();
            });

            bool connected = easyClient.ConnectAsync(serverEndpoint).Result;

            Assert.IsTrue(connected);

            easyClient.Send(Encoding.ASCII.GetBytes("#Hola!##"));

            callbackEvent.WaitOne(timeout);

            await easyClient.Close();

            appServer.Stop();
        }
Example #29
0
        public async Task F_AppSerserReplyToEasyClientNewRequestReceived()
        {
            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);

                s.Send("Hi There!");
            };

            EasyClient easyClient = new EasyClient();

            AutoResetEvent callbackEvent = new AutoResetEvent(false);

            easyClient.Initialize(new TestProtoBaseDefaultTerminatorReceiverFilter(), (p) =>
            {
                Assert.AreEqual("Hi There!", p.Key);

                callbackEvent.Set();
            });

            bool connected = easyClient.ConnectAsync(serverEndpoint).Result;

            Assert.IsTrue(connected);

            easyClient.Send(Encoding.ASCII.GetBytes("Hello!" + Environment.NewLine));

            callbackEvent.WaitOne(timeout);

            await easyClient.Close();

            appServer.Stop();
        }
Example #30
0
 public async Task <bool> Close()
 {
     return(await client.Close());
 }
Example #31
0
        /// <summary>
        /// 获取数据
        /// </summary>
        private void TaskStart()
        {
            Parallel.ForEach(YxjkJkds, jkd =>
            {
                Task.Factory.StartNew(async delegate
                {
                    var client = new EasyClient();

                    /***
                     * 初始化socket连接, 接受返回数据处理
                     * HxReceiveFilter为自定义的协议
                     * ***/
                    client.Initialize(new HxReceiveFilter(), (request) =>
                    {
                        try
                        {
                            string reqStr = request.Key + request.Body;
                            jkd.JKD_VALUE = reqStr;
                            jkd.CURR_TIME = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                        }
                        catch (Exception ex)
                        {
                            WriteLog(ex.Message, ExEnum.Error);
                        }
                    });
                    // Connect to the server
                    await client.ConnectAsync(new IPEndPoint(
                        IPAddress.Parse(Properties.Settings.Default.Service_Ip),
                        Properties.Settings.Default.Service_Port));
                    while (_taskFlag)
                    {
                        try
                        {
                            resend:
                            if (client.IsConnected)
                            {
                                //获取发送字符串
                                var enStr = GetSendStr(jkd.JKD_ID);
                                // Send data to the server
                                client.Send(Encoding.UTF8.GetBytes(enStr));
                            }
                            if (client.IsConnected == false && _taskFlag)
                            {
                                WriteLog($"{jkd.JKD_NAME}Socket连接失败,尝试重新连接...", ExEnum.Error);
                                await client.ConnectAsync(new IPEndPoint(
                                    IPAddress.Parse(Properties.Settings.Default.Service_Ip),
                                    Properties.Settings.Default.Service_Port));
                                goto resend;
                            }
                        }
                        catch (Exception e)
                        {
                            WriteLog(e.Message, ExEnum.Error);
                        }
                        finally
                        {
                            Thread.Sleep(Properties.Settings.Default.DelayTime);
                        }
                    }
                    await client.Close();
                    WriteLog($"{jkd.JKD_NAME} socket close", ExEnum.Infor);
                }, TaskCreationOptions.LongRunning);
            });
        }