static void TestEcho()
 {
     InstanceContext ctx = new InstanceContext(new CalculatorCallBack());
     EchoClient echo = new EchoClient(ctx);
     var result = echo.Echo("welcome to wcf!");
     Console.WriteLine(result);
 }
Exemple #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("starting sample runner");

            using (var scope = new TraceContextScope("Пример", TraceContextMode.New))
            {
                //Childs = new List<Process>() {
                //Process.Start(nameof(EchoApp))
                //, Process.Start(nameof(HelloApp))};

                AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                Console.WriteLine("wait...");
                Thread.Sleep(TimeSpan.FromSeconds(2));

                using (var echo = new EchoClient())
                    echo.Echo("Hello");

                using (var hello = new HelloClient())
                    hello.Hello();

                var txt = scope.Root.ToString();
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemple #3
0
        public void EchoMessage()
        {
            int port = 41717;

            using (var server = new EchoServer())
            {
                server.Start(port);

                using (var client = new EchoClient())
                {
                    var    sendMessage    = "abc";
                    string receiveMessage = null;

                    client.Connect(IPAddress.Loopback, port);
                    client.PacketReceived += reader =>
                    {
                        reader.Reset();
                        reader.Read <ushort>();
                        receiveMessage = reader.ReadString();
                    };
                    ClientToServer.Rpc.RequestEcho(client, sendMessage);
                    client.FlushPackets();

                    Waiting.Until(() => receiveMessage != null);

                    receiveMessage.Should().Be(sendMessage);
                }
            }
        }
 static void TestOneWay()
 {
     // NOTE it's really good to test the IsOneWay functionality, it works, as expected!
     InstanceContext ctx = new InstanceContext(new CalculatorCallBack());
     EchoClient echo = new EchoClient(ctx);
     Console.WriteLine("start to call SayHello...{0}", DateTime.Now);
     echo.SayHello("scotty");
     Console.WriteLine("end of calling SayHello...{0}", DateTime.Now);
 }
Exemple #5
0
        public Example(ILogger <Example> logger, EchoClient echoClient)
        {
            _logger         = logger;
            this.echoClient = echoClient;
            this.echoClient.OnNodeJoined += LogNodeJoined;

            //コントローラとしてふるまう
            this.echoClient.SelfNode.Devices.Add(
                new EchoObjectInstance(
                    EchoDotNetLite.Specifications.機器.管理操作関連機器.コントローラ, 0x01));
        }
        public void InvocationShouldAlwaysTriggerLaunchWhenMethodLaunchModeSetToAlways()
        {
            Task <GreetingResponse> HandleAsync(GreetingRequest greetingRequest, MethodCallContext context)
            {
                return(Task.FromResult(new GreetingResponse {
                    Greeting = greetingRequest.Name
                }));
            }

            RunWith10SecTimeout(async() =>
            {
                var serverCreatedCount = 0;
                var echoServerFactory  = new TestClientFactory(
                    (broker, id) =>
                {
                    var optionsBuilder = new ClientOptionsBuilder()
                                         .WithBrokerWorkingDir(_testBrokerFixture.SharedInstance.WorkingDir)
                                         .WithAppInstanceId(id)
                                         .WithApplicationId(EchoServerClient.Id)
                                         .WithDefaultConfiguration()
                                         .WithProvidedService(
                        GreetingService.Id,
                        "AlwaysLaunchGreetingService",
                        x => x.WithUnaryMethod <GreetingRequest, GreetingResponse>("Hello", HandleAsync));

                    serverCreatedCount++;

                    return(Task.FromResult(ClientFactory.Instance.Create(optionsBuilder.Build())));
                });

                var appLauncher = RegisterDisposable(
                    new TestAppLauncher(
                        _testBrokerFixture.SharedInstance,
                        new Dictionary <string, TestClientFactory>
                {
                    { EchoServerClient.Id, echoServerFactory }
                }
                        )
                    );
                await appLauncher.StartAsync();
                ConnectEchoServer();
                var client = new EchoClient(s => s.WithBrokerWorkingDir(_testBrokerFixture.SharedInstance.WorkingDir));
                client.ConnectAsync().ShouldCompleteIn(Timeout5Sec);
                var callDescriptor = new MethodCallDescriptor(
                    ProvidedMethodReference.Create(GreetingService.Id, "AlwaysLaunchGreetingService", "Hello", EchoServerClient.Id));
                await client.CallInvoker.CallUnary(callDescriptor, new GreetingRequest {
                    Name = "Test"
                });
                await client.CallInvoker.CallUnary(callDescriptor, new GreetingRequest {
                    Name = "Test"
                });
                serverCreatedCount.ShouldBe(2);
            });
        }
Exemple #7
0
    public static void Main(String[] args)
    {
        EchoClient conversant=null;
         StreamWriter swriter=null;
         StreamReader sreader=null;
         try {
        //Host name comes from command line
        //If no host specified, local machine is host
        String host=args.Length==1?args[0]:"127.0.0.1";

        //Connect to Echo server
        conversant=new EchoClient(host);

        //Get the stream between server and client
        NetworkStream ns=conversant.GetStream();

        //Create a user-friendly StreamWriter
        swriter=new StreamWriter(ns);

        //Create a user-friendly StreamReader
        sreader=new StreamReader(ns);

        //Prompt user for message to send to server
        //Period "exit" tells server to end session
        String input;
        Console.Write("Enter screen name: ");

        while ((input=Console.ReadLine())!="exit") {
        //Send message to server
        swriter.WriteLine(input);
        swriter.Flush();

        //Get the Echo from the server
        String returndata=sreader.ReadLine();
        Console.WriteLine("Reply from "+host+": "+returndata);
        Console.Write("Enter text: \"exit\" to stop: ");
        }

        //Send final message and scram
        swriter.WriteLine(".");
        swriter.Flush();

         } catch (Exception e) {
        Console.WriteLine(e+" "+e.StackTrace);
         } finally {
        //Close the connection whether exception thrown or not
        if (swriter!=null) swriter.Close();
        if (sreader!=null) sreader.Close();
        if (conversant!=null) conversant.Close();
         }
    }
Exemple #8
0
        static void Main(string[] args)
        {
            Trace.Listeners.Add(new ConsoleTraceListener());

            using (EchoClient client = new EchoClient()) {
                client.Port = 8088;
                client.Host = "localhost";
                client.Start();

                Console.WriteLine("Press enter key to exit...");
                Console.ReadLine();
                client.Stop();
            }
        }
Exemple #9
0
        static void Main(string[] args)
        {
            Logger.AddLogger(new ConsoleLogger());
            Logger.EnableAutoFlush();

            if (Arguments.TryParse(args, out var arguments) == false)
            {
                Console.WriteLine("Invalid arguments.\nUsage: Neti.EchoClient {IP} {Port}");
                Environment.Exit(1);
                return;
            }

            using (var echoClient = new EchoClient())
            {
                var serverId = $"{arguments.Ip}:{arguments.Port}";
                echoClient.Connected      += () => Console.WriteLine("# Connected! If you want to exit, type \"/exit\".");
                echoClient.PacketReceived += _ => Interlocked.Exchange(ref receiveMessageCheck, 1);
                echoClient.Disconnected   += () => Console.WriteLine("# Disconnected.");

                Console.WriteLine($"# Connecting to {serverId}...");
                echoClient.Connect(arguments.Ip, arguments.Port);

                if (echoClient.IsConnected == false)
                {
                    Console.WriteLine("# Failed to conntect.");
                    Environment.Exit(2);
                    return;
                }

                while (echoClient.IsConnected)
                {
                    Console.Write($"{serverId} < ");
                    var msg = Console.ReadLine();
                    if (msg == "/exit")
                    {
                        echoClient.Disconnect();
                        break;
                    }
                    Interlocked.Exchange(ref receiveMessageCheck, 0);
                    ClientToServer.Rpc.RequestEcho(echoClient, msg);
                    echoClient.FlushPackets();
                    while (receiveMessageCheck == 0)
                    {
                        Thread.Sleep(17);
                    }
                }
            }

            Environment.ExitCode = 0;
        }
Exemple #10
0
        public void Hello()
        {
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine("Hello");
            Console.ResetColor();

            using (var dbscope = new TraceContextScope("бд"))
            {
                Thread.Sleep(TimeSpan.FromSeconds(1));

                TraceContext.SetProperty("cs", "connection string");
            }

            using (var echo = new EchoClient())
                echo.Echo("вызов echo");
        }
Exemple #11
0
        static void Main(string[] args)
        {
            EchoClient client = new EchoClient();

            Console.Write("\nSending Echo request to service...");

            string result = client.Echo("Hello, DataCore!");

            Console.WriteLine("done");

            Console.WriteLine("Echo(\"Hello, DataCore!\") = {0}", result);

            Console.WriteLine("\nPress <Enter> to terminate the client.");
            Console.ReadLine();
            client.Close();
        }
Exemple #12
0
        static void Main()
        {
            // Note that the ListenUri must be communicated out-of-band.
            // That is, the metadata exposed by the service does not publish
            // the ListenUri, and thus the svcutil-generated config doesn't
            // know about it.

            // On the client, use ClientViaBehavior to specify
            // the Uri where the server is listening.
            Uri via = new Uri("http://localhost/ServiceModelSamples/service.svc");

            // Create a client to talk to the Calculator contract
            CalculatorClient calcClient = new CalculatorClient();

            calcClient.ChannelFactory.Endpoint.Behaviors.Add(
                new ClientViaBehavior(via));
            double value1 = 100.00D;
            double value2 = 15.99D;
            double result = calcClient.Add(value1, value2);

            Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
            calcClient.Close();

            // Create a client to talk to the Echo contract that is located
            // at the same EndpointAddress and ListenUri as the calculator contract
            EchoClient echoClient = new EchoClient("WSHttpBinding_IEcho");

            echoClient.ChannelFactory.Endpoint.Behaviors.Add(
                new ClientViaBehavior(via));
            Console.WriteLine(echoClient.Echo("Hello!"));
            echoClient.Close();

            // Create a client to talk to the Echo contract that is located
            // at a different EndpointAddress, but the same ListenUri
            EchoClient echoClient1 = new EchoClient("WSHttpBinding_IEcho1");

            echoClient1.ChannelFactory.Endpoint.Behaviors.Add(
                new ClientViaBehavior(via));
            Console.WriteLine(echoClient1.Echo("Hello!"));
            echoClient.Close();

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client application.");
            Console.ReadLine();
        }
Exemple #13
0
        private static async Task SendDataToServer(int messagesToSend)
        {
            using (var server = new MyEchoServer())
            {
                server.Start();

                var client = new MyEchoClient("127.0.0.1", 4444, 512);

                client.Connect();
                Assert.True(client.ConnectedToServer);

                for (var i = 0; i < messagesToSend; i++)
                {
                    client.SendRandomMessage();
                    await Task.Delay(10);
                }

                EchoClient clientFromServer = server.Clients.FirstOrDefault();
                Assert.NotNull(clientFromServer);

                // Wait for message
                while (clientFromServer.ReceivedData.Count < messagesToSend)
                {
                    await Task.Delay(10);
                }

                Assert.Equal(client.SendedData.Count, clientFromServer.ReceivedData.Count);

                for (var i = 0; i < messagesToSend; i++)
                {
                    string clientMessage  = client.SendedData.ElementAt(i);
                    string serverMesssage = clientFromServer.ReceivedData.ElementAt(i);

                    Assert.NotNull(clientMessage);
                    Assert.NotNull(serverMesssage);
                    Assert.Equal(clientMessage, serverMesssage);
                }

                client.Disconnect();
                Assert.False(client.ConnectedToServer);
                client.Dispose();
            }
        }
Exemple #14
0
        static void Main()
        {
            // Note that the ListenUri must be communicated out-of-band.
            // That is, the metadata exposed by the service does not publish
            // the ListenUri, and thus the svcutil-generated config doesn't
            // know about it.

            // On the client, use ClientViaBehavior to specify
            // the Uri where the server is listening.
            Uri via = new Uri("http://localhost/ServiceModelSamples/service.svc");

            // Create a client to talk to the Calculator contract
            CalculatorClient calcClient = new CalculatorClient();
            calcClient.ChannelFactory.Endpoint.Behaviors.Add(
                new ClientViaBehavior(via));
            double value1 = 100.00D;
            double value2 = 15.99D;
            double result = calcClient.Add(value1, value2);
            Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result);
            calcClient.Close();

            // Create a client to talk to the Echo contract that is located
            // at the same EndpointAddress and ListenUri as the calculator contract
            EchoClient echoClient = new EchoClient("WSHttpBinding_IEcho");
            echoClient.ChannelFactory.Endpoint.Behaviors.Add(
                new ClientViaBehavior(via));
            Console.WriteLine(echoClient.Echo("Hello!"));
            echoClient.Close();

            // Create a client to talk to the Echo contract that is located
            // at a different EndpointAddress, but the same ListenUri
            EchoClient echoClient1 = new EchoClient("WSHttpBinding_IEcho1");
            echoClient1.ChannelFactory.Endpoint.Behaviors.Add(
                new ClientViaBehavior(via));
            Console.WriteLine(echoClient1.Echo("Hello!"));
            echoClient.Close();

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client application.");
            Console.ReadLine();
        }
Exemple #15
0
        static void Main()
        {
            //Application.EnableVisualStyles();
            // Application.SetCompatibleTextRenderingDefault(false);
            // Application.Run(new Form1());
            // BufferTest.a();
            // System.Threading.Thread.Sleep(1000000);
            ConsumerContext.Init();
            ConsumerContext.lua.RegisterFunction("print", null, typeof(ConsumerManager).GetMethod("Print"));
            EchoClient.RunClientAsync().Wait();


            // System.Threading.Thread.CurrentThread.Suspend();
            System.Threading.Thread.Sleep(1000000);
            CodedInputStream             d;
            CodedOutputStream            b;
            ProtobufVarint32FrameDecoder c;

            // Console.WriteLine(Application.StartupPath);

            // Student student = new Student();

            Lua lua = new Lua();

            //lua.RegisterFunction("MethodA", student, student.GetType().GetMethod("MethodA"));
            lua.RegisterFunction("print", null, typeof(ConsumerManager).GetMethod("Print"));
            lua.DoFile("lua/LuaObj.lua");
            lua.RegisterFunction("print", null, typeof(ConsumerManager).GetMethod("Print"));
            // string path = "lua/com/senpure/io/ConsumerDecoder.lua";

            LuaFunction func = lua.GetFunction("hello");

            func.Call(new Student());

            // System.Threading.Thread.CurrentThread.Suspend();
        }
Exemple #16
0
    static void Main(string[] args)
    {
        var uv   = new xx.UvLoop();
        var conn = new EchoClient(uv);

        conn.SetAddress("0.0.0.0", 12345);
        conn.OnConnect = status =>
        {
            if (status != 0)
            {
                Console.WriteLine("connect failed.");
                return;
            }
            conn.SendBytes(new byte[1] {
                1
            });
        };
        conn.Connect();
        var sw = System.Diagnostics.Stopwatch.StartNew();

        uv.Run();
        Console.WriteLine(sw.ElapsedMilliseconds);
        Console.ReadLine();
    }
Exemple #17
0
 private void timerSendData_Tick(object sender, EventArgs e)
 {
     EchoClient.SendData(Convert.ToInt32(textBoxSendCount.Text));
 }
        public void InvocationShouldTriggerLaunchWithSingleInstanceModeByDefault()
        {
            var serverInvokedCount = 0;

            Task <GreetingResponse> HandleAsync(GreetingRequest greetingRequest, MethodCallContext context)
            {
                Interlocked.Increment(ref serverInvokedCount);
                return(Task.FromResult(new GreetingResponse {
                    Greeting = greetingRequest.Name
                }));
            }

            RunWith10SecTimeout(async() =>
            {
                var serverCreatedCount = 0;
                var echoServerFactory  = new TestClientFactory(
                    (broker, id) =>
                {
                    WriteLog("Launching server on demand");

                    var optionsBuilder = new ClientOptionsBuilder()
                                         .WithBrokerWorkingDir(_testBrokerFixture.SharedInstance.WorkingDir)
                                         .WithAppInstanceId(id)
                                         .WithApplicationId(EchoServerClient.Id)
                                         .WithDefaultConfiguration()
                                         .WithProvidedService(
                        GreetingService.Id,
                        x => x.WithUnaryMethod <GreetingRequest, GreetingResponse>("Hello", HandleAsync));

                    serverCreatedCount++;

                    return(ClientFactory.Instance.Create(optionsBuilder.Build()));
                });

                var appLauncher = RegisterDisposable(
                    new TestAppLauncher(
                        _testBrokerFixture.SharedInstance,
                        new Dictionary <string, TestClientFactory>
                {
                    { EchoServerClient.Id, echoServerFactory }
                }
                        )
                    );
                await appLauncher.StartAsync();
                var client = new EchoClient(s => s.WithBrokerWorkingDir(_testBrokerFixture.SharedInstance.WorkingDir));
                client.ConnectAsync().ShouldCompleteIn(Timeout5Sec);
                var callDescriptor = new MethodCallDescriptor(
                    ProvidedMethodReference.Create(GreetingService.Id, "Hello", EchoServerClient.Id));
                var call1 = client.CallInvoker.CallUnary(callDescriptor, new GreetingRequest {
                    Name = "Test"
                });
                var call2 = client.CallInvoker.CallUnary(callDescriptor, new GreetingRequest {
                    Name = "Test"
                });
                await Task.WhenAny(call1.AsTask(), call2.AsTask());
                WriteLog("Call 1 completed");
                await Task.WhenAll(call1.AsTask(), call2.AsTask());
                WriteLog("Call 2 completed");
                serverCreatedCount.ShouldBe(1);
                serverInvokedCount.ShouldBe(2);
            });
        }
Exemple #19
0
 private void buttonConCount_Click(object sender, EventArgs e)
 {
     EchoClient.RequestConnect(Convert.ToInt32(textBoxConCount.Text));
 }
Exemple #20
0
 private void buttonSend1_Click(object sender, EventArgs e)
 {
     EchoClient.SendData(1);
 }
Exemple #21
0
 private void buttonSendCount_Click(object sender, EventArgs e)
 {
     EchoClient.SendData(Convert.ToInt32(textBoxSendCount.Text));
 }
Exemple #22
0
 private void buttonInitEndPoint_Click(object sender, EventArgs e)
 {
     EchoClient.InitClient(textBoxIP.Text, Convert.ToInt32(textBoxPort.Text));
 }
Exemple #23
0
    public static void Main(String[] args)
    {
        EchoClient client = null;

        try
        {
            handler += new EventHandler(Handler);
            SetConsoleCtrlHandler(handler, true);

            //Host name comes from command line
            //If no host specified, local machine is host
            String host = args.Length == 1 ? args[0] : "127.0.0.1";

            //creates connection
            client = new EchoClient(host);

            //gets stream between server and client
            NetworkStream ns = client.GetStream();

            //creates writer and reader
            swriter = new StreamWriter(ns);
            sreader = new StreamReader(ns);

            //tells the user how to exit the chat properly
            Console.Write("Enter text: \"exit\" to leave the chat: \n");

            //prompts the user the screen name for this client
            String input;
            Console.Write("Enter screen name: ");

            //starts thread to read messages being sent from other clients
            //from the server
            Thread readthread = new Thread(new ThreadStart(client.Reader));
            readthread.Start();

            while ((input = Console.ReadLine()) != "exit")
            {
                //sends the message to the sever to be sent to
                //other clients
                swriter.WriteLine(input);
                swriter.Flush();
            }

            //tells the server that the client has left
            swriter.WriteLine("exit");
            swriter.Flush();

            //tell reader to stop reading
            endreader = true;

            //holds the console while it cleans up from exiting without typing "exit"
            while (!exitSystem)
            {
                Thread.Sleep(500);
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e + " " + e.StackTrace);
        }
    }
Exemple #24
0
 private void buttonSetBuffer_Click(object sender, EventArgs e)
 {
     EchoClient.InitBuffer(textBoxBufferText.Text);
 }
Exemple #25
0
 private void buttonCon100_Click(object sender, EventArgs e)
 {
     EchoClient.RequestConnect(100);
 }
 static void TestCallback()
 {
     InstanceContext ctx = new InstanceContext(new CalculatorCallBack());
     EchoClient client = new EchoClient(ctx);
     client.SayHello("scotty & juicy");
 }