I wrote a small link that creates a named pipe pipe and a client that connects to it. You can send data to the server, and the server reads it successfully.
The next thing I need to do is to receive messages from the server, so I have another thread that appears and sits and waits for incoming data.
The problem is that while the thread is sitting waiting for incoming data, you can no longer send messages to the server, since it hangs on a call WriteLine, since I assume that the channel is now connected with data verification.
Is it so simple that I don't approach this correctly? Or are called pipes that are not intended for such use? The examples that I saw in named pipes seem to go only one way, the client sends and receives the server, although you can specify the direction of the channel as In, Outor both.
Any help, pointers or suggestions would be appreciated!
Here is the code:
NamedPipeClientStream pipeClient;
StreamWriter swClient;
Thread messageReadThread;
bool listeningStopRequested = false;
public void Connect(string pipeName, string serverName = ".")
{
if (pipeClient == null)
{
pipeClient = new NamedPipeClientStream(serverName, pipeName, PipeDirection.InOut);
pipeClient.Connect();
swClient = new StreamWriter(pipeClient);
swClient.AutoFlush = true;
}
StartServerThread();
}
public void SendMessage(string msg)
{
if (swClient != null && pipeClient != null && pipeClient.IsConnected)
{
swClient.WriteLine(msg);
BeginListening();
}
}
public void StartServerThread()
{
listeningStopRequested = false;
messageReadThread = new Thread(new ThreadStart(BeginListening));
messageReadThread.IsBackground = true;
messageReadThread.Start();
}
public void BeginListening()
{
string currentAction = "waiting for incoming messages";
try
{
using (StreamReader sr = new StreamReader(pipeClient))
{
while (!listeningStopRequested && pipeClient.IsConnected)
{
string line;
while ((line = sr.ReadLine()) != null)
{
RaiseNewMessageEvent(line);
LogInfo("Message received: {0}", line);
}
}
}
LogInfo("Client disconnected");
RaiseDisconnectedEvent("Manual disconnection");
}
catch (IOException e)
{
string error = "Connection terminated unexpectedly: " + e.Message;
LogError(currentAction, error);
RaiseDisconnectedEvent(error);
}
}
source
share