C# NamedPipeServerStream Ping pong

579 views Asked by At

I try to make a server and client application with NamedPipeServerStream and NamedPipeClientStream, let me try to explain, what i want to do:

-There will be a server -There will be many clients -Each client connect to server -Each client send messages to server, and server send a result. Assume that making hand shake between server and client. As far I as know, if you connect client to server using NamedPipeClientStream and NamedPipeServerStream there is a way between them bidirectional so after i connect client to server, also server available to send message to client too, but i does not work. Client sends message to server, after that server gets message and sends back it to client. however, server can not send. Please check it where is the problem ? Thank You

Server Codes

 class Program
{
    static NamedPipeServerStream serverPipe;
    static byte[] buffer = new byte[1024];
    static void Main(string[] args)
    {
        serverPipe = new NamedPipeServerStream("myPipe", PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
        serverPipe.BeginWaitForConnection(new AsyncCallback(GetClient), serverPipe);
        Console.ReadLine();            
    }

    public static void GetClient(IAsyncResult result)
    {          
        serverPipe = (NamedPipeServerStream)result.AsyncState;
        serverPipe.EndWaitForConnection(result);
        serverPipe.BeginRead(buffer, 0, 1024, new AsyncCallback(GetMessage), serverPipe);            
    }

    public static void GetMessage(IAsyncResult result)
    {           
        int length=serverPipe.EndRead(result);
        string stringResult=UTF8Encoding.UTF8.GetString(buffer);
        Console.WriteLine("Client says: " + stringResult);
        //server write throws exception, if i even make clients status to begin read
        serverPipe.Write(buffer, 0, buffer.Length);
    }
}

Client codes:

    //CLIENT
class Program
{
    static NamedPipeClientStream clientPipe;
    static void Main(string[] args)
    {
        clientPipe = new NamedPipeClientStream("myPipe");

        if (!clientPipe.IsConnected)
        {
            clientPipe.Connect();
        }

        Console.WriteLine("Session started");
        while (true)
        {
            string message = Console.ReadLine();
            byte[] byteArray = Encoding.UTF8.GetBytes(message);
            clientPipe.Write(byteArray, 0, byteArray.Length);
            //should it be a beginread here ? it is also did not work . there is something wrong with  in serverPipe.Write() in servers code

        }
    }
}
0

There are 0 answers