When using C # NamedPipeServerStream in case the client does not send any pattern-end message (for example, \ r \ n when the server is reading using ReadLine ()) Reading methods NamedPipeServerStream will wait forever, and Abort () or Interupt ( ) will work on this thread.
FROM:
1) Stream.ReadTimeout is not supported for NamedPipeServerStream
2) Abort () or Interupt () does not work in the stream
3) NamedPipeServerStream.Disconnect () bottom work
It is unclear how to set the timeout in NamedPipeServerStream read operations.
Let me give you an example. The IPC specification requires the exchange of strings with a null number. The client sends a message, the server processes the message and sends a response as it should. If the client does not send \ 0 at the end (the client is not ours, therefore, we cannot guarantee the correctness of its operation), the Read method will always wait, and the client (since we do not control it) can always wait for an answer too.
The following is a simplified implementation example:
public void RestartServer() { _pipeServerThread.Interrupt(); //doesn't affect Read wait _pipeServerThread.Abort(); //doesn't affect Read wait } private void PipeServerRun(object o) //runs on _pipeServerThread { _pipeServer = new NamedPipeServerStream(_pipeName, InOut, 100, PipeTransmissionMode.Message, PipeOptions.WriteThrough); //_pipeServer.ReadTimeout = 100; //System.InvalidOperationException: Timeouts are not supporte d on this stream. // Wait for a client to connect while (true) { _pipeServer.WaitForConnection(); string request = ReadPipeString(); //... process request, send response and disconnect } } /// <summary> /// Read a \0 terminated string from the pipe /// </summary> private string ReadPipeString() { StringBuilder builder = new StringBuilder(); var streamReader = new StreamReader(_pipeServer); while (true) { //read next byte char[] chars = new char[1]; streamReader.Read(chars, 0, 1); // <- This will wait forever if no \0 and no more data from client if (chars[0] == '\0') return builder.ToString(); builder.Append(chars[0]); } }
So how to set a timeout for NamedPipeServerStream read operations?
Majesticra
source share