基本上,我有一个C#控制台应用程序和一个node.js脚本通过命名管道进行通信。但是,一切都按预期进行,如果node.js脚本终止并重新连接,则C#端通常将失败,并显示错误“ System.IO.Exception:管道已损坏”。
问题是试图让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文件管道/命名管道说的很新,因此我不确定这是否可能。