/// <summary> /// Send a string down the pipe using Unicode encoding. /// Only the first MaxBytes will be sent, meaning the max /// string length is MaxBytes / BytesPerChar. /// </summary> public bool WriteMessage(string message) { try { if (clientPipe != null && clientPipe.IsConnected) { // Don't use a StreamWriter here because it has buffering which messes up the synchronization // of messages across the pipe. byte[] bytes = Encoding.Unicode.GetBytes(message); int len = bytes.Length; byte[] header = new byte[4]; header[0] = (byte)(len & 0xff); header[1] = (byte)((len >> 8) & 0xff); header[2] = (byte)((len >> 16) & 0xff); header[3] = (byte)((len >> 24) & 0xff); clientPipe.Write(header, 0, 4); clientPipe.Write(bytes, 0, len); clientPipe.Flush(); } } catch (IOException) { return(false); } return(true); }
private void EndSendMessage(IAsyncResult result) { lock (_InstanceLock) { _Stream.EndWrite(result); _Stream.Flush(); } }
/// <summary> /// Überträgt ein Objekt in eine Kommunikationseinheit. /// </summary> /// <param name="pipe">Die Kommunikationseinheit.</param> /// <param name="serializer">Die Serialisierungsinstanz.</param> /// <param name="instance">Das betroffene Objekt.</param> internal static void SendToPipe(PipeStream pipe, XmlSerializer serializer, object instance) { // Create helper using (var temp = new MemoryStream()) { // Create writer configuration var settings = new XmlWriterSettings { CheckCharacters = false }; // Create using (var writer = XmlWriter.Create(temp, settings)) serializer.Serialize(writer, instance); // Read data and create buffer for length var len = new byte[sizeof(long)]; var data = temp.ToArray(); // Lock briefly var lenLock = GCHandle.Alloc(len, GCHandleType.Pinned); try { // Fill Marshal.WriteInt64(lenLock.AddrOfPinnedObject(), data.LongLength); } finally { // Release lenLock.Free(); } // Send all pipe.Write(len, 0, len.Length); // Write in blocks for (int n = 0; n < data.Length;) { // Block size int block = Math.Min(BlockSize, data.Length - n); // Send chunck pipe.Write(data, n, block); pipe.Flush(); // Advance n += block; } // Flush pipe.Flush(); pipe.WaitForPipeDrain(); } }
protected override void Act() { _pipeStream.Flush(); // give async read time to complete _readThread.Join(100); }
public static void WriteStream <T>(PipeStream stream, RpcPipeContext context, T data) { byte[] contextBuffer = ProtoBufSerializer.ToByteArray <RpcPipeContext>(context); byte[] bodyBuffer = null; if (typeof(T) != typeof(RpcNull)) { bodyBuffer = ProtoBufSerializer.ToByteArray <T>(data); } else { bodyBuffer = EmptyBuffer; } RpcPipeHeader header; header.Mark = RpcPipeHeader.MagicMark; header.ContextSize = contextBuffer.Length; header.BodySize = bodyBuffer.Length; byte[] headerBuffer = RpcPipeHeader.ToByteArray(header); stream.Write(headerBuffer, 0, headerBuffer.Length); stream.Write(contextBuffer, 0, contextBuffer.Length); if (header.BodySize > 0) { stream.Write(bodyBuffer, 0, bodyBuffer.Length); } stream.Flush(); }
public int WriteString(string outString) { byte[] outBuffer = streamEncoding.GetBytes(outString); int len = outBuffer.Length; if (len > UInt16.MaxValue) { len = (int)UInt16.MaxValue; } try { pipeStream.WriteByte((byte)(len / 256)); pipeStream.WriteByte((byte)(len & 255)); pipeStream.Write(outBuffer, 0, len); pipeStream.Flush(); } catch (Exception ex) { if (!pipeStream.IsConnected) { Console.WriteLine("Disconnected"); } throw; } return(outBuffer.Length + 2); }
/// <summary> /// Uploads the specified directory to the remote host. /// </summary> /// <param name="directoryInfo">Local directory to upload.</param> /// <param name="filename">Remote host directory name.</param> /// <exception cref="ArgumentNullException"><paramref name="directoryInfo"/> or <paramref name="filename"/> is null.</exception> public void Upload(DirectoryInfo directoryInfo, string filename) { if (directoryInfo == null) { throw new ArgumentNullException("directoryInfo"); } if (filename == null) { throw new ArgumentNullException("filename"); // TODO: Should add IsNullOrWhitespace for this filename parameter? } // UNDONE: EnsureConnection? using (var input = new PipeStream()) using (var channel = this.Session.CreateChannel <ChannelSession>()) { channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e) { input.Write(e.Data, 0, e.Data.Length); input.Flush(); }; channel.Open(); // Send channel command request channel.SendExecRequest(string.Format("scp -qrt \"{0}\"", filename)); this.CheckReturnCode(input); this.InternalUpload(channel, input, directoryInfo, filename); channel.Close(); } }
protected void Act() { _pipeStream.Flush(); // give async read time to complete _asyncReadResult.AsyncWaitHandle.WaitOne(100); }
/// <summary> /// Downloads the specified file from the remote host to local file. /// </summary> /// <param name="filename">Remote host file name.</param> /// <param name="fileInfo">Local file information.</param> /// <exception cref="ArgumentNullException"><paramref name="fileInfo"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="filename"/> is null or empty.</exception> public void Download(string filename, IStorageFile fileInfo) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentException("filename"); } if (fileInfo == null) { throw new ArgumentNullException("fileInfo"); } using (var input = new PipeStream()) using (var channel = Session.CreateChannelSession()) { channel.DataReceived += delegate(object sender, ChannelDataEventArgs e) { input.Write(e.Data, 0, e.Data.Length); input.Flush(); }; channel.Open(); // Send channel command request channel.SendExecRequest(string.Format("scp -pf \"{0}\"", filename)); SendConfirmation(channel); // Send reply InternalDownload(channel, input, fileInfo); channel.Close(); } }
public bool Send(string message, bool flush = false, bool wait = false) { if (!_connected) { return(false); } try { var output = Encoding.UTF8.GetBytes(message); Debug.Assert(output.Length < IpcLib.ServerInBufferSize); _pipe.BeginWrite(output, 0, output.Length, OnAsyncWriteComplete, _pipe); if (flush) { _pipe.Flush(); } if (wait && RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { _pipe.WaitForPipeDrain(); } } catch (Exception) { _pipe.Close(); } return(true); }
/// <summary> /// Downloads the specified directory from the remote host to local directory. /// </summary> /// <param name="directoryName">Remote host directory name.</param> /// <param name="directoryInfo">Local directory information.</param> /// <exception cref="ArgumentNullException"><paramref name="directoryInfo"/> or <paramref name="directoryName"/> is null.</exception> public void Download(string directoryName, DirectoryInfo directoryInfo) { if (directoryInfo == null) { throw new ArgumentNullException("directoryInfo"); } if (string.IsNullOrEmpty(directoryName)) { throw new ArgumentException("directoryName"); } using (var input = new PipeStream()) using (var channel = this.Session.CreateChannel <ChannelSession>()) { channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e) { input.Write(e.Data, 0, e.Data.Length); input.Flush(); }; channel.Open(); // Send channel command request channel.SendExecRequest(string.Format("scp -prf \"{0}\"", directoryName)); this.SendConfirmation(channel); // Send reply this.InternalDownload(channel, input, directoryInfo); channel.Close(); } }
public void FlushTest() { PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value target.Flush(); Assert.Inconclusive("A method that does not return a value cannot be verified."); }
internal void ProcessSendMessages() { IBuffer[] items; if (IsDisposed) { return; } if (System.Threading.Interlocked.CompareExchange(ref mSendStatus, 1, 0) == 0) { BufferLink bufferLink = new BufferLink(); object data = DequeueSendMessage(); if (data == null) { System.Threading.Interlocked.Exchange(ref mSendStatus, 0); return; } PipeStream pipStream = Stream.ToPipeStream(); while (data != null) { if (data is IBuffer) { bufferLink.Import((IBuffer)data); } else if (data is IBuffer[]) { items = (IBuffer[])data; for (int i = 0; i < items.Length; i++) { bufferLink.Import(items[i]); } } else if (data is IEnumerable <IBuffer> ) { foreach (IBuffer item in (IEnumerable <IBuffer>)data) { bufferLink.Import(item); } } else { WriterData(data, pipStream); } data = DequeueSendMessage(); } if (SSL && pipStream.CacheLength > 0) { pipStream.Flush(); } IBuffer streamBuffer = mBaseNetStream.GetWriteCacheBufers(); bufferLink.Import(streamBuffer); if (bufferLink.First != null) { CommitBuffer(bufferLink.First); } else { System.Threading.Interlocked.Exchange(ref mSendStatus, 0); } } }
/// <summary> /// Flushed streams need to be connected, if not ignore /// </summary> public void Flush() { if (pipeStream.IsConnected) { pipeStream.Flush(); } }
/// <summary> /// write data to a named pipe /// </summary> /// <param name="pipe"></param> /// <param name="pipeName">named pipes don't have a "Name" property... passing it as param (used for error log)</param> /// <param name="message"></param> public static void WritePipeMessage( PipeStream pipe, string pipeName, string message) { try { if (pipe != null && pipe.IsConnected && pipe.CanWrite) { var buffer = Encoding.UTF8.GetBytes(message); pipe.Write(buffer, 0, buffer.Length); pipe.Flush(); } else { Trace.TraceError("Failed to write message to pipe {0} (not ready)", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName)); } } catch (IOException) { Trace.TraceError("Failed to write message to pipe {0} (I/O error)", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName)); } catch (Exception exc) { Trace.TraceError("Failed to write message to pipe {0} ({1})", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName), exc); } }
protected PipeWriter(PipeStream pipeStream) { _pipeStream = pipeStream ?? throw new ArgumentNullException(nameof(pipeStream)); _binaryWriter = new BinaryWriter(_memoryStream); _argsWriter = new BuildEventArgsWriter(_binaryWriter); new Thread(() => { BuildEventArgs eventArgs; while ((eventArgs = TakeEventArgs()) != null) { // Reset the memory stream (but reuse the memory) _memoryStream.Seek(0, SeekOrigin.Begin); _memoryStream.SetLength(0); // Buffer to the memory stream _argsWriter.Write(eventArgs); _binaryWriter.Flush(); // ...then write that to the pipe _memoryStream.WriteTo(_pipeStream); _pipeStream.Flush(); } _doneProcessing.Set(); }).Start(); }
/// <summary> /// Uploads the specified file to the remote host. /// </summary> /// <param name="fileInfo">The file system info.</param> /// <param name="path">The path.</param> /// <exception cref="System.ArgumentNullException">fileSystemInfo</exception> /// <exception cref="System.ArgumentException">path</exception> /// <exception cref="System.NotSupportedException"></exception> /// <exception cref="ArgumentNullException"><paramref name="fileInfo" /> or <paramref name="filename" /> is null.</exception> public void Upload(FileInfo fileInfo, string path) { if (fileInfo == null) { throw new ArgumentNullException("fileSystemInfo"); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException("path"); } using (var input = new PipeStream()) using (var channel = this.Session.CreateChannel <ChannelSession>()) { channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e) { input.Write(e.Data, 0, e.Data.Length); input.Flush(); }; channel.Open(); // Send channel command request channel.SendExecRequest(string.Format("scp -t \"{0}\"", path)); this.CheckReturnCode(input); this.InternalUpload(channel, input, fileInfo, fileInfo.Name); channel.Close(); } }
public int WriteString(string outString) { if (this.ioStream == null) { return(0); } if (!this.ioStream.IsConnected) { return(0); } try { byte[] outBuffer = streamEncoding.GetBytes(outString); int len = outBuffer.Length; if (len > UInt16.MaxValue) { len = (int)UInt16.MaxValue; } var debug1 = (byte)(len / 256); var debug2 = (byte)(len & 255); ioStream.WriteByte((byte)(len / 256)); ioStream.WriteByte((byte)(len & 255)); ioStream.Write(outBuffer, 0, len); ioStream.Flush(); return(outBuffer.Length + 2); } catch { return(0); } }
protected override void SendData(byte[] data) { #if NET45 || NETCOREAPP2_0 _Stream.Write(data, 0, data.Length); _Stream.Flush(); #endif }
public static void WriteStreamEx(PipeStream stream, RpcPipeContext context, Exception ex) { byte[] contextBuffer = ProtoBufSerializer.ToByteArray <RpcPipeContext>(context); byte[] bodyBuffer = null; if (ex != null) { bodyBuffer = BinarySerializer.ToByteArray(ex); } else { bodyBuffer = EmptyBuffer; } RpcPipeHeader header; header.Mark = RpcPipeHeader.MagicMark; header.ContextSize = contextBuffer.Length; header.BodySize = bodyBuffer.Length; byte[] headerBuffer = RpcPipeHeader.ToByteArray(header); stream.Write(headerBuffer, 0, headerBuffer.Length); stream.Write(contextBuffer, 0, contextBuffer.Length); if (header.BodySize > 0) { stream.Write(bodyBuffer, 0, bodyBuffer.Length); } stream.Flush(); }
/// <summary> /// Uploads the specified stream to the remote host. /// </summary> /// <param name="source">Stream to upload.</param> /// <param name="path">Remote host file name.</param> public void Upload(Stream source, string path) { using (var input = new PipeStream()) using (var channel = this.Session.CreateClientChannel <ChannelSession>()) { channel.DataReceived += delegate(object sender, ChannelDataEventArgs e) { input.Write(e.Data, 0, e.Data.Length); input.Flush(); }; channel.Open(); int pathEnd = path.LastIndexOfAny(new[] { '\\', '/' }); if (pathEnd != -1) { // split the path from the file string pathOnly = path.Substring(0, pathEnd); string fileOnly = path.Substring(pathEnd + 1); // Send channel command request channel.SendExecRequest(string.Format("scp -t \"{0}\"", pathOnly)); this.CheckReturnCode(input); path = fileOnly; } this.InternalUpload(channel, input, source, path); channel.Close(); } }
public void WriteToReadOnlyPipe_Throws_NotSupportedException() { if (SupportsBidirectionalReadingWriting) { return; } using (ServerClientPair pair = CreateServerClientPair()) { PipeStream pipe = pair.readablePipe; Assert.True(pipe.IsConnected); Assert.False(pipe.CanWrite); Assert.False(pipe.CanSeek); Assert.Throws <NotSupportedException>(() => pipe.Write(new byte[5], 0, 5)); Assert.Throws <NotSupportedException>(() => pipe.WriteByte(123)); Assert.Throws <NotSupportedException>(() => pipe.Flush()); Assert.Throws <NotSupportedException>(() => pipe.OutBufferSize); Assert.Throws <NotSupportedException>(() => pipe.WaitForPipeDrain()); Assert.Throws <NotSupportedException>(() => { pipe.WriteAsync(new byte[5], 0, 5); }); } }
/// <summary> /// Async callback for when this client was done sending a message. /// </summary> /// <param name="result">The result.</param> private void EndSendMessage(IAsyncResult result) { try { lock (_streamLock) { _stream.EndWrite(result); _stream.Flush(); bool flushStateFlag = (bool)result.AsyncState; if (flushStateFlag) { int newValue = Interlocked.Decrement(ref _messagesFlushedCounter); if (newValue <= 0) { // setting the semaphore will make the WaitOne in Flush() continue. _flushSemaphore.Set(); _isFlushing = false; } } } } catch { this.Disconnect(); } }
public static void WriteMessage(this PipeStream stream, string message) { var responseBytes = Encoding.UTF8.GetBytes(message); stream.Write(responseBytes, 0, responseBytes.Length); stream.Flush(); stream.WaitForPipeDrain(); }
private void EndSendMessage(IAsyncResult result) { lock (mNamedPipeLock) { mStream.EndWrite(result); mStream.Flush(); } }
public void Write(string message) { var bytes = _streamEncoding.GetBytes(message); Contract.Assert(MESSAGE_SIZE_MAX >= bytes.Length); pipeStream.Write(bytes, 0, bytes.Length); pipeStream.Flush(); }
/// <summary> /// write data to a named pipe /// </summary> /// <param name="pipe"></param> /// <param name="pipeName"></param> /// <param name="message"></param> /// <param name="sizeHeader"></param> public static void WritePipeMessage( PipeStream pipe, string pipeName, string message, bool sizeHeader = false) { if (pipe == null) { Trace.TraceError("Failed to write message to pipe {0} (not set)", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName)); return; } if (!pipe.IsConnected) { Trace.TraceError("Failed to write message to pipe {0} (not connected)", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName)); return; } try { if (pipe.CanWrite) { byte[] buffer; if (sizeHeader) { using (var memoryStream = new MemoryStream()) { memoryStream.Write(BitConverter.GetBytes(message.Length), 0, 4); memoryStream.Write(Encoding.UTF8.GetBytes(message), 0, message.Length); buffer = memoryStream.ToArray(); } } else { buffer = Encoding.UTF8.GetBytes(message); } pipe.Write(buffer, 0, buffer.Length); pipe.Flush(); } else { throw new Exception("not writable"); } } catch (IOException) { Trace.TraceWarning("Failed to write message to pipe {0} (I/O error)", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName)); throw; } catch (Exception exc) { Trace.TraceError("Failed to write message to pipe {0} ({1})", (string.IsNullOrEmpty(pipeName) ? "<unknown>" : pipeName), exc); throw; } }
public static void OtherSidePipeDisconnectWriteThrows(PipeStream pipe) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws <IOException>(() => pipe.Write(buffer, 0, buffer.Length)); Assert.Throws <IOException>(() => pipe.WriteByte(123)); Assert.Throws <IOException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); }); Assert.Throws <IOException>(() => pipe.Flush()); }
public static void AfterDisconnectWriteOnlyPipeThrows(PipeStream pipe) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws <InvalidOperationException>(() => pipe.Write(buffer, 0, buffer.Length)); Assert.Throws <InvalidOperationException>(() => pipe.WriteByte(5)); Assert.Throws <InvalidOperationException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); }); Assert.Throws <InvalidOperationException>(() => pipe.Flush()); }
public static void SendRequest <T>(this PipeStream stream, byte[] req, T obj) { _bytesBuffer.Clear(); _bytesBuffer.AddRange(req); _bytesBuffer.AddRange(MessagePackSerializer.Serialize(obj)); stream.Write(BitConverter.GetBytes(_bytesBuffer.Count), 0, 4); stream.Write(_bytesBuffer.ToArray(), 0, _bytesBuffer.Count); stream.Flush(); }
public static void AfterDisconnectWriteOnlyPipeThrows(PipeStream pipe) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<InvalidOperationException>(() => pipe.Write(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => pipe.WriteByte(5)); Assert.Throws<InvalidOperationException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); } ); Assert.Throws<InvalidOperationException>(() => pipe.Flush()); }
public static void OtherSidePipeDisconnectWriteThrows(PipeStream pipe) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<IOException>(() => pipe.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => pipe.WriteByte(123)); Assert.Throws<IOException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); } ); Assert.Throws<IOException>(() => pipe.Flush()); }
public static void ConnectedPipeReadOnlyThrows(PipeStream pipe) { Assert.True(pipe.IsConnected); Assert.False(pipe.CanWrite); Assert.Throws<NotSupportedException>(() => pipe.Write(new byte[5], 0, 5)); Assert.Throws<NotSupportedException>(() => pipe.WriteByte(123)); Assert.Throws<NotSupportedException>(() => pipe.Flush()); Assert.Throws<NotSupportedException>(() => pipe.OutBufferSize); Assert.Throws<NotSupportedException>(() => pipe.WaitForPipeDrain()); Assert.Throws<NotSupportedException>(() => { pipe.WriteAsync(new byte[5], 0, 5); } ); }
public static void WhenDisposedPipeThrows(PipeStream pipe) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<ObjectDisposedException>(() => pipe.Write(buffer, 0, buffer.Length)); Assert.Throws<ObjectDisposedException>(() => pipe.WriteByte(5)); Assert.Throws<ObjectDisposedException>(() => { pipe.WriteAsync(buffer, 0, buffer.Length); } ); Assert.Throws<ObjectDisposedException>(() => pipe.Flush()); Assert.Throws<ObjectDisposedException>(() => pipe.Read(buffer, 0, buffer.Length)); Assert.Throws<ObjectDisposedException>(() => pipe.ReadByte()); Assert.Throws<ObjectDisposedException>(() => { pipe.ReadAsync(buffer, 0, buffer.Length); } ); Assert.Throws<ObjectDisposedException>(() => pipe.IsMessageComplete); }