Sto cercando un buon esempio in cui NamedPipeServerStream e NamedPipeServerClient possono inviare messaggi a vicenda (quando PipeDirection = PipeDirection.InOut per entrambi). Per ora ho trovato solo this msdn article. Ma descrive solo il server. Qualcuno sa come dovrebbe apparire il client che si connette a questo server?Esempio su NamedPipeServerStream vs NamedPipeServerClient con PipeDirection.InOut necessario
18
A
risposta
33
Quello che succede è che il server si siede in attesa di una connessione, quando ne ha uno manda una stringa "In attesa" come una semplice stretta di mano, il client legge quindi questo e lo verifica quindi rimanda una stringa di "Test Message" (nella mia app è in realtà la riga di comando args).
Ricorda che il WaitForConnection
sta bloccando, quindi probabilmente vorrai eseguirlo su un thread separato.
class NamedPipeExample
{
private void client() {
var pipeClient = new NamedPipeClientStream(".",
"testpipe", PipeDirection.InOut, PipeOptions.None);
if (pipeClient.IsConnected != true) { pipeClient.Connect(); }
StreamReader sr = new StreamReader(pipeClient);
StreamWriter sw = new StreamWriter(pipeClient);
string temp;
temp = sr.ReadLine();
if (temp == "Waiting") {
try {
sw.WriteLine("Test Message");
sw.Flush();
pipeClient.Close();
}
catch (Exception ex) { throw ex; }
}
}
stessa classe, metodo Server
private void server() {
var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4);
StreamReader sr = new StreamReader(pipeServer);
StreamWriter sw = new StreamWriter(pipeServer);
do {
try {
pipeServer.WaitForConnection();
string test;
sw.WriteLine("Waiting");
sw.Flush();
pipeServer.WaitForPipeDrain();
test = sr.ReadLine();
Console.WriteLine(test);
}
catch (Exception ex) { throw ex; }
finally {
pipeServer.WaitForPipeDrain();
if (pipeServer.IsConnected) { pipeServer.Disconnect(); }
}
} while (true);
}
}
Grazie! Mi hai aiutato a capire qual era il problema con il mio codice. Stavo lasciando il server in attesa di leggere qualcosa dal client (in un thread separato), e nello stesso tempo stava cercando di inviare un messaggio al client. Il codice era sospeso su sw.WriteLine. Sembra che non sia possibile per il server attendere il messaggio e inviarne uno nello stesso tempo. – Nat
Semplice e chiaro. +1 – Artiom
Questa è la soluzione più semplice e pulita (senza DllImport) trovata. Grazie! – Lensflare