我正在尝试使用NamedPipe。我创建了两个基于控制台的应用程序。一种是用于客户端,另一种是用于服务器。
客户代码:
class Program
{
static void Main(string[] args)
{
long total = 0;
Stopwatch stopWatch = new Stopwatch();
Stopwatch stopWatch2 = new Stopwatch();
stopWatch2.Start();
for (int i = 0; i < 10000; i++)
{
stopWatch.Restart();
var client = new Client()
{
Name = "Client" + i,
ClientStream = new NamedPipeClientStream("testPipe"),
};
client.ClientStream.Connect();
if (client.ClientStream.IsConnected)
{
client.Multiply(2);
var x = stopWatch.ElapsedMilliseconds;
Console.WriteLine(i + ": Time : " + x);
client.ClientStream.Dispose();
client.ClientStream.Close();
total += x;
}
}
Console.WriteLine("Total: " + stopWatch2.ElapsedMilliseconds);
Console.WriteLine("Average: " + total / 10000);
Console.ReadLine();
}
}
服务器代码:
public class PipeServer
{
public static void Main(string[] args)
{
Console.WriteLine("Waiting for client to connect:");
NamedPipeServerStream pipeServer = new NamedPipeServerStream("testPipe", PipeDirection.InOut, 4);
while (!pipeServer.IsConnected)
{
pipeServer.WaitForConnection();
Console.WriteLine("Client Connected");
try
{
if (pipeServer.IsConnected)
{
var data = pipeServer.ReadByte();
pipeServer.WriteByte((byte)(data * 2));
}
}
catch (Exception ex)
{
}
finally
{
pipeServer.Disconnect();
Console.WriteLine("Client Disconnected");
}
}
}
}
客户端模型:
public class Client
{
public string Name { get; set; }
public NamedPipeClientStream ClientStream { get; set; }
public int Multiply(int x)
{
ClientStream.WriteByte(2);
var data = ClientStream.ReadByte();
return data;
}
}
因此,当我在Mono上运行此应用程序时,它会连接而不会启动服务器。但是,这些相同的代码在Windows .Net Framework 4.7上也可以完美地工作。 有谁知道为什么在Mono上会发生这种情况?