Search code examples
c#node.jsstreamnamed-pipes

c# to Node.js - Flushing named pipe write buffer does not end stream


I'm writing two Windows applications (one C# and one Electron) that communicates with each other using named pipes. The c# client should send the message and then flush to end that message. But the NamedPipeClientStream does not end streams on the Node side when flushing the buffer:

// C# client
public class Client
{
    private NamedPipeClientStream _client;
    private StreamWriter _writer;

    public Client(string pipeName)
    {
        InitClient();
    }

    private void InitClient()
    {
        _client = new NamedPipeClientStream("myPipe");
        _writer = new StreamWriter(_client);
        _client.Connect();
    }

    public void SendMessage(string response)
    {
        _writer.Write(response);
        _writer.Flush();
    }
}

This sends messages to a Node.js receiver:

// Node.js server
export class MessageHandler {
  private _pipePath;
  private _server: Server;
  private _stream: Socket;
  private _messageBuffer = "";

  constructor() {
    this._pipePath = "\\\\.\\pipe\\myPipe";
    this.initiateServer();
  }

  public initiateServer() {
    this._server = createServer({ allowHalfOpen: true }, (socket: Socket) => {
      this._stream = socket;

      this._stream.on("data", (buffer: Buffer) => {
        const message = buffer.toString();

        this._messageBuffer += message;
      });

      this._stream.on("end", () => {
        this.handleMessage();
      });
    });
  }

  private handleMessage() {
    ...
  }
}

I thought flushing the stream would trigger an end to the message?

What am I missing? Can I manually send an end to the stream from the C# client that I can detect in the Node side?

Thanks!


Solution

  • You need to Close your _writer and _client after use, in order for them to release.

    Your SendMessage should look like so:

    _writer.Write(response);
    _writer.Flush();
    _writer.Close();
    _client.Close();