static void ProcessWStr(this NamedPipeServerStream Server) { var Buffer = Server.ReadStringBuffer(); fixed(void *pStr = &Buffer[0]) { var Rst = EntryPoint.ProcessW(pStr); if (Rst == pStr) { Server.WriteI32(0); Server.Flush(); return; } WCString NewStr = Rst; var StrData = NewStr.ToArray(); StrData = StrData.Concat(new byte[2]).ToArray(); Server.WriteI32(StrData.Length); Server.Write(StrData, 0, StrData.Length); Server.Flush(); } }
public void SendToClient(string str) { byte[] outBuffer = Encoding.UTF8.GetBytes(str); int len = outBuffer.Length; pipeServer.WriteByte((byte)(len / 256)); pipeServer.WriteByte((byte)(len % 256)); pipeServer.Write(outBuffer, 0, len); pipeServer.Flush(); }
private void ServerThread() //pipe server thread { NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1); Debug.Log("Wait For Client"); pipeServer.WaitForConnection(); Debug.Log("Client connected "); int width = Screen.width; int height = Screen.height; /* * // these code use to tansfer pictue size, here we use default size * pipeServer.WriteByte ((byte)(width / 256)); * pipeServer.WriteByte ((byte)(width & 255)); * pipeServer.WriteByte ((byte)(height / 256)); * pipeServer.WriteByte ((byte)(height & 255)); * pipeServer.Flush (); */ while (pipeServer.IsConnected) { byte[][] transferdata = imagedata; int len = transferdata[0].Length; Debug.Log("Picture length: " + len); // transfer R G B matrix of picture to the client pipeServer.Write(transferdata[0], 0, len); pipeServer.Flush(); pipeServer.Write(transferdata[1], 0, len); pipeServer.Flush(); pipeServer.Write(transferdata[2], 0, len); pipeServer.Flush(); // receive distance data from client int receivedata = -1; receivedata = pipeServer.ReadByte() * 256; receivedata += pipeServer.ReadByte(); if (receivedata != -1) { distance = receivedata; } Debug.Log("distance = " + distance); Thread.Sleep(500); } pipeServer.Close(); }
public bool SendMessage(string msg) { var ret = false; if (_pipeServer == null) { return(ret); } if (_pipeServer.IsConnected) { try { byte[] data = encoding.GetBytes(msg); _pipeServer.Write(data, 0, data.Length); _pipeServer.Flush(); _pipeServer.WaitForPipeDrain(); ret = true; } catch (Exception ex) { Logger.LogError4Exception(ex); } } return(ret); }
public void Send(string msg) { var data = _utf8.GetBytes(msg); _server.Write(data, 0, data.Length); _server.Flush(); }
private void testServeTable(NamedPipeServerStream serve) { Task read = new Task(() => { while (serve.CanRead) { ArrayList listjson = new ArrayList(); int len = ReadLength(serve); byte[] data = new byte[len]; serve.Read(data, 0, len); string date = "2019-1"; string name = "卢"; string address = "浙江"; DateTime time = System.DateTime.Now; for (var i = 0; i < 2000; i++) { var obj = new JObject { { "date", date }, { "name", name }, { "address", address }, { "time", time } }; listjson.Add(obj); } string json = JsonConvert.SerializeObject(listjson); //将JSON对象转化为字符串 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json); //接受后立马发送返回信息的测试 serve.Write(bytes, 0, bytes.Length); serve.Flush(); } }); read.Start(); //serve.Disconnect(); }
/* * private void RunLoggerLooper() { * * NamedPipeServerStream logPipeServer = null; * while (_shouldRun) * { * // Allocate the named pipe endpoint * logPipeServer = new NamedPipeServerStream(LOG_PIPE, PipeDirection.InOut, -1, PipeTransmissionMode.Message, PipeOptions.None, INBUFFSIZE, OUTBUFFSIZE, _pipeSa); * * // Wait for a client to connect * logPipeServer.WaitForConnection(); * * //Spawn a new thread for each request and continue waiting * Thread t = new Thread(ProcessLogging); * t.Start(logPipeServer); * } * logPipeServer.Close(); * } */ void ProcessLogging(NamedPipeServerStream logPipeServer) { //NamedPipeServerStream logPipeServer = o as NamedPipeServerStream; try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. var log_msg = ProcessSingleReceivedMessage(logPipeServer); ProgramStatus.Instance.IncLogRate(); //Console.Out.WriteLine(log_msg); LogSyscall(log_msg); // Send the ACK ( ACK = 1 ) logPipeServer.Write(ENCODED_ACK, 0, ENCODED_ACK.Length); logPipeServer.Flush(); logPipeServer.Disconnect(); } catch (Exception e) { try { if (logPipeServer.IsConnected) { logPipeServer.Disconnect(); } } catch (Exception e1) { // GIVEUP } } }
private static void ReceiveDataByPipe(object hWnd) { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream( CommonString.PipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte)) { while (true) { pipeServer.WaitForConnection(); byte[] bytesWrite = Encoding.Default.GetBytes(CommonString.MainFormTitle); pipeServer.Write(bytesWrite, 0, bytesWrite.Length); pipeServer.Flush(); byte[] bytes = new byte[1024]; int length = pipeServer.Read(bytes, 0, 1024); string strTemp = Encoding.Default.GetString(bytes, 0, length); if (strTemp[0] == '0' && strTemp[1] == '1') { CommonString.WebSearchKeyWord = strTemp.Substring(2); ShowSearchResultAction?.BeginInvoke(null, null); } pipeServer.Disconnect(); if (strTemp[0] == '1') { break; } } } }
public async Task OperationsOnDisconnectedServer() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; pair.Connect(); Assert.Throws <InvalidOperationException>(() => server.IsMessageComplete); Assert.Throws <InvalidOperationException>(() => server.WaitForConnection()); await Assert.ThrowsAsync <InvalidOperationException>(() => server.WaitForConnectionAsync()); // fails because allowed connections is set to 1 server.Disconnect(); Assert.Throws <InvalidOperationException>(() => server.Disconnect()); // double disconnect byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (pair.writeToServer) { Assert.Throws <InvalidOperationException>(() => server.Write(buffer, 0, buffer.Length)); Assert.Throws <InvalidOperationException>(() => server.WriteByte(5)); Assert.Throws <InvalidOperationException>(() => { server.WriteAsync(buffer, 0, buffer.Length); }); } else { Assert.Throws <InvalidOperationException>(() => server.Read(buffer, 0, buffer.Length)); Assert.Throws <InvalidOperationException>(() => server.ReadByte()); Assert.Throws <InvalidOperationException>(() => { server.ReadAsync(buffer, 0, buffer.Length); }); } Assert.Throws <InvalidOperationException>(() => server.Flush()); Assert.Throws <InvalidOperationException>(() => server.IsMessageComplete); Assert.Throws <InvalidOperationException>(() => server.GetImpersonationUserName()); } }
private void ServerThread() //pipe server thread { NamedPipeServerStream pipeServer = new NamedPipeServerStream("HarryThePipe", PipeDirection.InOut); //Create the named pipe, named SuperPipe, can send and recieve data UnityEngine.Debug.Log("Wait For Client"); pipeServer.WaitForConnection(); //Wait until client connects to server; wait for MATLAB to connect through attached c# code UnityEngine.Debug.Log("Client connected "); StreamBytes serverStream = new StreamBytes(pipeServer); while (pipeServer.IsConnected) { while (activeValues) { for (int simMonth = monthStart; simMonth <= monthFinish; simMonth++) { monthSun = simMonth; for (int simDay = dayStart; simDay <= dayFinish; simDay++) { daySun = simDay; for (int simHour = hourStart; simHour <= hourFinish; simHour++) { hourSun = simHour; Thread.Sleep(120); for (int i = 0; i < 6; i++) { serverStream.WriteBytes(Math.Round(cellSpace[i], 1)); pipeServer.Flush(); } Thread.Sleep(100); dataFromClient = serverStream.ReadBytes(); dataFromClient1 = serverStream.ReadBytes(); dataFromClient2 = serverStream.ReadBytes(); Save(simMonth, simDay, simHour, Math.Round(dataFromClient, 1)); Thread.Sleep(850); } if ((simMonth == 2 && simDay == 28) || ((simMonth == 4 || simMonth == 6 || simMonth == 9 || simMonth == 11) && simDay == 30)) { simDay = 32; } UnityEngine.Debug.Log("End of Day"); } //Collect only July and January //if (simMonth == 1) //{ // simMonth = 6; //} //else if (simMonth == 7) //{ // simMonth = 12; //} } activeValues = false; } } pipeServer.Close(); }
private static void pipe_server(string pipeName) { var serverPipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None, 4096, 4096); while (true) { Console.WriteLine("wait connect"); serverPipe.WaitForConnection(); Console.WriteLine("connected"); var writer = new StreamWriter(serverPipe); var reader = new StreamReader(serverPipe); writer.AutoFlush = true; string data = reader.ReadLine(); Console.WriteLine($"Received : {data}"); writer.WriteLine(data); serverPipe.Flush(); serverPipe.Disconnect(); } }
/// <summary> /// NamedPipeServerStream Server端 /// /// 建立管線 /// /// Client 透過 PipeName 來連線 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Task.Run(() => { NamedPipeServerStream stream = null; Console.WriteLine("start server in thread " + Thread.CurrentThread.ManagedThreadId); // maxNumberOfServerInstances = 允許建立相同PipeName的個數 stream = new NamedPipeServerStream("NamedPipeServerStream_Test", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None); while (true) { Console.WriteLine("before WaitForConnection()"); stream.WaitForConnection(); Thread.Sleep(1000); int newId = ++_newId; byte[] bytes = BitConverter.GetBytes(newId); stream.Write(bytes, 0, bytes.Length); stream.Flush(); Console.WriteLine($"[{DateTime.Now:yyyyMMdd hhmmss}]Send newId: {newId}."); stream.Disconnect(); } }); Console.Read(); }
void DoListen() { while (true) { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(pipePath, PipeDirection.InOut, numPipeThreads, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, (int)Protocol.MaxMessageLength, (int)Protocol.MaxMessageLength)) { Console.WriteLine("Waiting for client on path " + pipePath); pipeServer.WaitForConnection(); Console.WriteLine("Client connected"); ServerConnection conn; if (!AcceptClient(pipeServer, out conn)) { Console.WriteLine("Client rejected"); pipeServer.Disconnect(); continue; } pipeServer.Flush(); pipeServer.WaitForPipeDrain(); if (NewConnection != null) { NewConnection(conn); } while (conn.IsConnected) { conn.Iterate(); } pipeServer.Disconnect(); } } }
private void Dispose(bool managed) { lock (this) { if (_emmePipe != null) { // Send our termination message first try { using var writer = new BinaryWriter(_emmePipe, Encoding.UTF8, true); writer.Write(SignalTermination); writer.Flush(); _emmePipe.Flush(); // after our message has been sent then we can go and kill the stream _emmePipe.Dispose(); _emmePipe = null; } catch (IOException) { } } if (managed) { GC.SuppressFinalize(this); } } }
public static void ClientDisconnectedPipeThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer2", PipeDirection.InOut)) { using (NamedPipeClientStream client = new NamedPipeClientStream("testServer2")) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); clientConnect1.Wait(); Assert.True(client.IsConnected); Assert.True(server.IsConnected); client.Dispose(); Assert.Throws <IOException>(() => server.Write(buffer, 0, buffer.Length)); Assert.Throws <IOException>(() => server.WriteByte(123)); Assert.Throws <IOException>(() => server.Flush()); int length = server.Read(buffer, 0, buffer.Length); Assert.Equal(0, length); int byt = server.ReadByte(); } } }
/// <summary> /// Pipe发送数据任务 /// </summary> /// <param name="cancelFlag">停止标志</param> static void PipeSendTaskWork(CancellationToken cancelFlag) { Logger.HistoryPrinting(Logger.Level.INFO, MethodBase.GetCurrentMethod().DeclaringType.FullName, "Console msg server pipe transfer begins to send datas."); while (true) { if (cancelFlag.IsCancellationRequested) { break; } byte[] pipeDatas = PopFromQueue(QueueNum.TcpToPipe); if (Object.Equals(pipeDatas, null)) { Thread.Sleep(waitTimerMsForBuffer); continue; } try { innerPipe.Write(pipeDatas, 0, pipeDatas.Length); innerPipe.Flush(); } catch (Exception ex) { throw ex; } } pipeRecieveCancel.Cancel(); // 发送停止,则接收也准备停止 Logger.HistoryPrinting(Logger.Level.INFO, MethodBase.GetCurrentMethod().DeclaringType.FullName, "Console msg server pipe transfer stops to send datas."); }
/// <summary> /// /// </summary> /// <param name="args"></param> static void Main(string[] args) { Console.Title = "命名管道-服务端"; using (NamedPipeServerStream namedPipeServerStream = new NamedPipeServerStream(NAMED_PIPE_SERVER)) { try { Console.WriteLine("等待客户端连接..."); namedPipeServerStream.WaitForConnection(); Console.WriteLine("客户端已连接..."); while (true) { byte[] buffer = System.Text.Encoding.UTF8.GetBytes("My name is lichaoqiang!"); namedPipeServerStream.Write(buffer, 0, buffer.Length); namedPipeServerStream.Flush(); System.Threading.Thread.Sleep(2000); } } catch (System.IO.IOException ex) { Console.WriteLine(ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } } Console.ReadLine(); }
//////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// protected virtual void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { try { namedPipeServerStream.Flush(); namedPipeServerStream.Close(); } catch (IOException) { Console.WriteLine("Pipe already closed"); } catch (InvalidOperationException) { Console.WriteLine("Pipe already closed"); } } disposed = true; }
public void Close() { if (_stream == null) { return; } if (_closingMsg != null) { _stream.Write(_closingMsg, 0, _closingMsg.Length); _stream.Flush(); } _stream.Dispose(); _stream = null; }
/* * Read the data from the serial port */ void read_data() { try { var len = (int)br.ReadUInt32(); // Read string length datareceived = new string(br.ReadChars(len)); // Read string UnityEngine.Debug.Log(datareceived); server.Flush(); } catch (EndOfStreamException) { UnityEngine.Debug.Log("server disconnected"); server.Close(); server.Dispose(); isConnected = false; } }
public void Write_to_Client_Async(string message) { if (namedPipeServerStream != null) { if (namedPipeServerStream.CanWrite && namedPipeServerStream.IsConnected) { namedPipeServerStream.WaitForPipeDrain(); ASCIIEncoding.ASCII.GetBytes(message).CopyTo(write_buffer, 0); namedPipeServerStream.BeginWrite(write_buffer, 0, write_buffer.Length, new AsyncCallback(Async_Write_Completed), 2); namedPipeServerStream.Flush(); } else { close_pipe(); } } }
private void Regenerate() { try { _pipe?.Flush(); } catch { // ignored } _pipe?.Dispose(); ConnectedClient = null; _pipe = new NamedPipeServerStream(_configuration.PipeName, PipeDirection.InOut, _configuration.MaxServerInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, _configuration.InBufferSize, _configuration.OutBufferSize); }
private void WriteCommandAsyncCallback(IAsyncResult result) { if (CommandStream != null && CommandStream.IsConnected) { CommandStream.EndWrite(result); CommandStream.Flush(); } }
/// <summary> /// List the unit tests available to the pipe as single message. /// </summary> private void ListTests() { try { // Build test suite from the given assembly. TestSuite testSuite = new TestBuilder().Build(assemblyName, true); // Recursively browse tests and concatenate full test names to string in separate lines. Queue <ITest> testQueue = new Queue <ITest>(); testQueue.Enqueue(testSuite); String testNames = "Tests:"; while (testQueue.Count > 0) { ITest test = testQueue.Dequeue(); if (test.Tests != null) { foreach (ITest childTest in test.Tests) { testQueue.Enqueue(childTest); } } else { if (testNames.Length > 0) { testNames += "\n"; } testNames += test.TestName.FullName; } } // Write test names to the pipe. byte[] testNameBytes = Encoding.UTF8.GetBytes(testNames); pipe.Write(testNameBytes, 0, testNameBytes.Length); pipe.Flush(); } catch (Exception) { // Write empty test names to the pipe. byte[] testNameBytes = Encoding.UTF8.GetBytes("Tests:"); pipe.Write(testNameBytes, 0, testNameBytes.Length); pipe.Flush(); } }
private void WaitForConnectionCallBack(IAsyncResult iar) { try { // Get the pipe NamedPipeServerStream pipeServer = (NamedPipeServerStream)iar.AsyncState; // End waiting for the connection pipeServer.EndWaitForConnection(iar); byte[] buffer = new byte[1024]; // Read the incoming message pipeServer.Read(buffer, 0, 1024); // Convert byte buffer to string string jsonRequestMsg = Encoding.UTF8.GetString(buffer, 0, buffer.Length); IpcOperationType type = IpcMessageStore.getIpcOperationType(jsonRequestMsg); string jsonResponseMsg = null; if (type == IpcOperationType.AddIssueRequest) { AddIssueResponse response = handleAddIssueRequest(); jsonResponseMsg = IpcMessageStore.savePayload(IpcOperationType.AddIssueResponse, response); } else if (type == IpcOperationType.OpenViewpointRequest) { VisualizationInfo visInfo = IpcMessageStore.getPayload <VisualizationInfo>(jsonRequestMsg); jsonResponseMsg = "{}"; doOpen3DView(visInfo); } else if (type == IpcOperationType.SelectElementsRequest) { List <Component> components = IpcMessageStore.getPayload <List <Component> >(jsonRequestMsg); jsonResponseMsg = "{}"; selectElements(components, true); } // Send response byte[] _buffer = Encoding.UTF8.GetBytes(jsonResponseMsg); pipeServer.Write(_buffer, 0, _buffer.Length); pipeServer.Flush(); // Kill original sever and create new wait server pipeServer.Close(); pipeServer = null; pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); // Recursively wait for the connection again and again.... pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private void WriteLoop() { var videoPipeName = $"flaui-capture-{Guid.NewGuid()}"; var ffmpegIn = new NamedPipeServerStream(videoPipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 10000, 10000); const string pipePrefix = @"\\.\pipe\"; Process ffmpegProcess = null; var isFirstFrame = true; ImageData lastImage = null; while (!_frames.IsCompleted) { _frames.TryTake(out var img, -1); if (img == null) { // Happens when the queue is marked as completed continue; } if (isFirstFrame) { isFirstFrame = false; Directory.CreateDirectory(new FileInfo(TargetVideoPath).Directory.FullName); var videoInFormat = _settings.UseCompressedImages ? "" : "-f rawvideo"; // Used when sending raw bitmaps to the pipe var videoInArgs = $"-framerate {_settings.FrameRate} {videoInFormat} -pix_fmt rgb32 -video_size {img.Width}x{img.Height} -i {pipePrefix}{videoPipeName}"; var videouOutCodec = _settings.VideoFormat == VideoFormat.x264 ? $"-c:v libx264 -crf {_settings.VideoQuality} -pix_fmt yuv420p -preset ultrafast" : $"-c:v libxvid -qscale:v {_settings.VideoQuality}"; var videoOutArgs = $"{videouOutCodec} -r {_settings.FrameRate} -vf \"scale={img.Width.Even()}:{img.Height.Even()}\""; ffmpegProcess = StartFFMpeg(_settings.ffmpegPath, $"-y -hide_banner -loglevel warning {videoInArgs} {videoOutArgs} \"{TargetVideoPath}\""); ffmpegIn.WaitForConnection(); } if (img.IsRepeatFrame) { // Repeat the last frame ffmpegIn.WriteAsync(lastImage.Data, 0, lastImage.Data.Length); } else { // Write the received frame and save it as last image ffmpegIn.WriteAsync(img.Data, 0, img.Data.Length); if (lastImage != null) { lastImage.Dispose(); lastImage = null; GC.Collect(); } lastImage = img; } } ffmpegIn.Flush(); ffmpegIn.Close(); ffmpegIn.Dispose(); ffmpegProcess?.WaitForExit(); ffmpegProcess?.Dispose(); }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _ffmpegIn.Flush(); _ffmpegIn.Close(); _audioPipe?.Flush(); _audioPipe?.Dispose(); _ffmpegProcess.WaitForExit(); }
public void SendMessage(Packet Message) { if (Pipe.IsConnected) { byte[] MessageBytes = Message.ToPacket(); Pipe.Write(MessageBytes, 0, MessageBytes.Length); Pipe.Flush(); SetOnPipeSent(Message); } }
private void ThreadNamedPipeServer(object data) { NamedPipeServerStream PipeStream = null; try { while (!Terminating) { lock (ThreadLock) { if (Terminating) { return; } var sec = new PipeSecurity(); sec.AddAccessRule( new PipeAccessRule(WindowsIdentity.GetCurrent().Name, PipeAccessRights.FullControl, AccessControlType.Allow)); PipeStream = new NamedPipeServerStream( PipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, sec); } try { PipeStream.WaitForConnection(); if (Terminating) { PipeStream.Dispose(); return; } else { StreamReader Reader = new StreamReader(PipeStream, Encoding.UTF8); StreamWriter Writer = new StreamWriter(PipeStream, Encoding.UTF8); string SearchTitle = Reader.ReadLine(); string[] Lines = GetDataLines(SearchTitle); foreach (string s in Lines) { Writer.WriteLine(s); } Writer.Flush(); PipeStream.Flush(); PipeStream.Close(); PipeStream.Dispose(); } } catch { } } } catch { } }
internal void Publish(byte[] data) { try { NativeMessageSerializer.WriteMessage(pipe, data); pipe.Flush(); } catch (Exception ex) { Log.Debug(ex, ex.Message); } }
public static async Task ClientDisconnectedPipeThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer2", PipeDirection.Out)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer2", PipeDirection.In)) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); client.Dispose(); Assert.Throws<IOException>(() => server.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => server.WriteByte(123)); Assert.Throws<IOException>(() => server.Flush()); } using (NamedPipeServerStream server = new NamedPipeServerStream("testServer2", PipeDirection.In)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer2", PipeDirection.Out)) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); client.Dispose(); server.Read(buffer, 0, buffer.Length); server.ReadByte(); } if (Interop.IsWindows) // Unix implementation of InOut doesn't fail on server.Write/Read when client disconnects due to allowing for additional connections { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer2", PipeDirection.InOut)) using (NamedPipeClientStream client = new NamedPipeClientStream("testServer2")) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); client.Dispose(); Assert.Throws<IOException>(() => server.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => server.WriteByte(123)); Assert.Throws<IOException>(() => server.Flush()); int length = server.Read(buffer, 0, buffer.Length); Assert.Equal(0, length); int byt = server.ReadByte(); } } }