我尝试使用NamedPipeServerStream和NamedPipeClientStream创建服务器和客户端应用程序,让我试着解释一下,我想做什么:
- 将有一台服务器 - 会有很多客户 - 每个客户端连接到服务器 - 每个客户端向服务器发送消息,服务器发送结果。假设在服务器和客户端之间进行握手。据我所知,如果你使用NamedPipeClientStream和NamedPipeServerStream将客户端连接到服务器,它们之间有一种双向方式,所以在我将客户端连接到服务器之后,服务器也可用于向客户端发送消息,但我不能正常工作。在服务器获取消息并将其发送回客户端之后,客户端将消息发送到服务器。但是,服务器无法发送。请检查问题出在哪里?谢谢
服务器代码
class Program
{
static NamedPipeServerStream serverPipe;
static byte[] buffer = new byte[1024];
static void Main(string[] args)
{
serverPipe = new NamedPipeServerStream("myPipe", PipeDirection.InOut, 100, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
serverPipe.BeginWaitForConnection(new AsyncCallback(GetClient), serverPipe);
Console.ReadLine();
}
public static void GetClient(IAsyncResult result)
{
serverPipe = (NamedPipeServerStream)result.AsyncState;
serverPipe.EndWaitForConnection(result);
serverPipe.BeginRead(buffer, 0, 1024, new AsyncCallback(GetMessage), serverPipe);
}
public static void GetMessage(IAsyncResult result)
{
int length=serverPipe.EndRead(result);
string stringResult=UTF8Encoding.UTF8.GetString(buffer);
Console.WriteLine("Client says: " + stringResult);
//server write throws exception, if i even make clients status to begin read
serverPipe.Write(buffer, 0, buffer.Length);
}
}
客户代码:
//CLIENT
class Program
{
static NamedPipeClientStream clientPipe;
static void Main(string[] args)
{
clientPipe = new NamedPipeClientStream("myPipe");
if (!clientPipe.IsConnected)
{
clientPipe.Connect();
}
Console.WriteLine("Session started");
while (true)
{
string message = Console.ReadLine();
byte[] byteArray = Encoding.UTF8.GetBytes(message);
clientPipe.Write(byteArray, 0, byteArray.Length);
//should it be a beginread here ? it is also did not work . there is something wrong with in serverPipe.Write() in servers code
}
}
}