Невозможно переподключить именованный канал из nodejs в C # после завершения - PullRequest
0 голосов
/ 31 мая 2019

По сути, у меня есть консольное приложение C # и скрипт node.js, взаимодействующие через именованный канал.Однако все работает так, как ожидалось. Если сценарий node.js завершается и подключается заново, на стороне C # обычно возникает ошибка «System.IO.Exception: Pipe is broken».

Проблема, с которой я пытался получить на стороне nodejs переподключение и заново установил соединение с именованным каналом.

Если у вас есть какие-либо советы / рекомендации, это было бы очень признательно.

Вот сторона C #, ее консольное приложение

using System;
using System.IO;
using System.IO.Pipes;

namespace testApp
{
    static class Program
    {
        static System.Timers.Timer waitInterval;
        static string pipeName = "testpipe";
        static NamedPipeClientStream CLIENT;
        static StreamReader reader = null;
        static StreamWriter writer = null;
        static void Main()
        {


            CreateConnection();

        }
        static void CreateConnection()
        {
            if(CLIENT != null)
            {
                CLIENT.Dispose();
            }
                CLIENT = new NamedPipeClientStream(pipeName); // this is blocking code
                CLIENT.Connect();

            //if (reader != null) reader.Dispose();
            //if (writer != null && writer) writer.Dispose();

            Console.WriteLine($"Creating connection {CLIENT.IsConnected}");
            try
            {
                using (reader = new StreamReader(CLIENT))
                {
                    using (writer = new StreamWriter(CLIENT){ AutoFlush = true})
                    {

                        while (true)
                        {
                            if (!CLIENT.IsConnected)
                            {
                                break;
                            }
                            var line = reader.ReadLine();
                            Console.WriteLine(line);
                            writer.WriteLine($"GOT Data : {line}");
                            writer.Flush();
                        }
                    }
                }
            }
            catch (Exception err)
            {
                CLIENT.Dispose();
                Console.WriteLine("Error creating connection");
                waitInterval = new System.Timers.Timer(5000);
                waitInterval.Enabled = true;
                waitInterval.Elapsed += (sender, e) =>
                {
                    Console.WriteLine("Reconnecting");
                    CreateConnection();
                };
                waitInterval.Start();
                Console.WriteLine("waiting for pipe...");
            }
        }
    }
}

node-ipc.js

А вот скрипт node.js

const net = require("net");

const server = net.createServer((stream) => {
  console.log("Server: on connection");

  stream.on("data", (buffer) => {
    console.log("Got data:", buffer.toString());
  });

  stream.on("end", () => {
    console.log("Stream ended");
    server.close();
  });
  setInterval(()=>{
    stream.write(`${Math.random()} \r\n`);

  }, 5000)
});

server.listen("\\\\.\\pipe\\testpipe", () => {
  console.log("Listening...");
});

Если у вас есть какие-либо советы / рекомендации, это будет с благодарностью.Я должен быть честным и сказать, что я новичок в C # и Windows file pipe / именованные каналы, поэтому я не уверен, возможно ли это вообще.

...