Communicate Between Processes - CSharp Operating System

CSharp examples for Operating System:Process

Description

Communicate Between Processes

Demo Code


using System;/*from  w  ww .  java 2  s.  c  o m*/
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Pipes;

class MainClass
    {
        static void Main(string[] args)
        {
            pipeClient();
            //pipeServer();
        }

        static void pipeServer()
        {
            NamedPipeServerStream pipestream = new NamedPipeServerStream("recipe_05_26_pipe");
            Console.WriteLine("Waiting for a client connection");
            pipestream.WaitForConnection();
            Console.WriteLine("Received a client connection");
            StreamReader reader = new StreamReader(pipestream);
            StreamWriter writer = new StreamWriter(pipestream);
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Writing message ", i);
                writer.WriteLine("Message {0}", i);
                writer.Flush();
            }
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Received: {0}", reader.ReadLine()); ;
            }
            pipestream.Close();
        }

        static void pipeClient()
        {
            NamedPipeClientStream pipestream = new NamedPipeClientStream("recipe_05_26_pipe");
            pipestream.Connect();

            StreamReader reader = new StreamReader(pipestream);
            StreamWriter writer = new StreamWriter(pipestream);

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Received: {0}", reader.ReadLine());
            }
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Writing response ", i);
                writer.WriteLine("Response {0}", i);
                writer.Flush();
            }
            pipestream.Close();
        }
    }

Result


Related Tutorials