private void Regenerate() { try { _pipe?.Flush(); } catch { // ignored } _pipe?.Dispose(); _pipe = new NamedPipeClientStream(".", _configuration.PipeName, PipeDirection.InOut, PipeOptions.Asynchronous); }
/// <summary> /// Closes the pipe /// </summary> public void Close() { //If we are already closed, jsut exit if (_isClosed) { Logger.Warning("Tried to close a already closed pipe."); return; } //flush and dispose try { //Wait for the stream object to become available. lock (l_stream) { if (_stream != null) { try { //Stream isn't null, so flush it and then dispose of it.\ // We are doing a catch here because it may throw an error during this process and we dont care if it fails. _stream.Flush(); _stream.Dispose(); } catch (Exception) { //We caught an error, but we dont care anyways because we are disposing of the stream. } //Make the stream null and set our flag. _stream = null; _isClosed = true; } else { //The stream is already null? Logger.Warning("Stream was closed, but no stream was available to begin with!"); } } } catch (ObjectDisposedException) { //ITs already been disposed Logger.Warning("Tried to dispose already disposed stream"); } finally { //For good measures, we will mark the pipe as closed anyways _isClosed = true; _connectedPipe = -1; } }
public static void SendMessage(TMessage message) { using (var pipeClient = new NamedPipeClientStream(".", PIPENAME, PipeDirection.Out, PipeOptions.None)) { pipeClient.Connect(); formatter.Serialize(pipeClient, message); pipeClient.Flush(); pipeClient.WaitForPipeDrain(); pipeClient.Close(); } }
/// <summary> /// Unsubscribe this instance. /// </summary> public virtual void Unsubscribe() { objConfiguration = null; if (pipeClient != null) { if (pipeClient.IsConnected) { pipeClient.Flush(); pipeClient.Close(); } pipeClient.Dispose(); } }
static void SendMessage(NamedPipeClientStream namedPipeClient, string message) { if (!namedPipeClient.IsConnected) { namedPipeClient.Connect(); namedPipeClient.ReadMode = PipeTransmissionMode.Message; } string serialised = JsonConvert.SerializeObject(message); byte[] messageBytes = Encoding.UTF8.GetBytes(serialised); namedPipeClient.Write(messageBytes, 0, messageBytes.Length); namedPipeClient.Flush(); }
public void TestOneWay_FlatFile_ISO88591() { PipeSecurity ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule("USERS", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); //We first spin a pipe server to make sure that the send port will be able to connect using (NamedPipeServerStream pipeServer = new NamedPipeServerStream( "OneWaySend", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024, ps)) { string ffContent = "303330123333777;ABCD;00001;00002;2014-01-15;21:21:33.444;EFGH;"; OutboundTestHelper testHelper = new OutboundTestHelper(pipeServer); pipeServer.BeginWaitForConnection(cb => testHelper.ClientConnected(cb), testHelper); //Here we spin the pipe client that will send the message to BizTalk using (NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "OneWayReceive", PipeDirection.InOut, PipeOptions.Asynchronous)) { byte[] flatBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(ffContent); pipeClient.Connect(10000); pipeClient.Write(flatBytes, 0, flatBytes.Count()); pipeClient.Flush(); pipeClient.WriteByte(0x00);//writing the EOF byte pipeClient.Flush(); pipeClient.WaitForPipeDrain(); } //Here we wait for the event to be signalled testHelper.syncEvent.WaitOne(60000); //The event was signalled, we get the message stirng from the outBuffer string receivedMsg = Encoding.GetEncoding("ISO-8859-1").GetString(testHelper.memStream.ToArray(), 0, (int)testHelper.memStream.Length); Assert.AreEqual(ffContent, receivedMsg, "Contents of the received message is different"); } }
internal static IWebHost CreateWebHost(HttpsConnectionFilterOptions httpsOptions) { var webHostBuilder = new WebHostBuilder() .UseLoggerFactory(_loggerFactory) .UseConfiguration(Configuration) .UseKestrel(options => { if (httpsOptions != null) { options.UseHttps(httpsOptions); } //options.UseConnectionLogging(); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>(); var webHost = webHostBuilder.Build(); var serverAddresses = webHost.ServerFeatures.Get <IServerAddressesFeature>(); string pipeName = _startupOptions.WriteServerUrlsToPipe; if (pipeName != null) { NamedPipeClientStream pipe; try { pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out); pipe.Connect(10000); } catch (IOException ex) { _logger.LogCritical(0, ex, Resources.Critical_InvalidPipeHandle, pipeName); throw; } catch (System.TimeoutException ex) { _logger.LogCritical(0, ex, Resources.Critical_PipeConnectTimeOut, pipeName); throw; } var applicationLifetime = webHost.Services.GetService <IApplicationLifetime>(); applicationLifetime.ApplicationStarted.Register(() => Task.Run(() => { using (pipe) { string serverUriStr = JsonConvert.SerializeObject(serverAddresses.Addresses); _logger.LogTrace(Resources.Trace_ServerUrlsToPipeBegin, pipeName, Environment.NewLine, serverUriStr); var serverUriData = Encoding.UTF8.GetBytes(serverUriStr); pipe.Write(serverUriData, 0, serverUriData.Length); pipe.Flush(); } _logger.LogTrace(Resources.Trace_ServerUrlsToPipeDone, pipeName); })); } return(webHost); }
private void AsyncSend(IAsyncResult iar) { try { NamedPipeClientStream namedPipeClientStream = (NamedPipeClientStream)iar.AsyncState; namedPipeClientStream.EndWrite(iar); namedPipeClientStream.Flush(); namedPipeClientStream.Close(); namedPipeClientStream.Dispose(); } catch (Exception) { } }
static void Client() { using (NamedPipeClientStream client = new NamedPipeClientStream(".", NAME, PipeDirection.InOut )) { Console.WriteLine("Connecting to server ..."); client.Connect(); client.ReadMode = PipeTransmissionMode.Message; Console.WriteLine("Connected."); while (true) { Byte[] randbytes = File.ReadAllBytes(@".\MStore.pdb"); CommandMessage cm = new CommandMessage { meta = "Q", data = "Data", blob = randbytes }; String cms = CommandSerializers.Serialize(cm); var cmsBytes = Encoding.ASCII.GetBytes(cms); CommandSerializers.WriteGreen( "Client sends REQUEST of ({0}: Serialized as: {1}\n", cmsBytes.Length, cms); try { client.Write(cmsBytes, 0, cms.Length); client.Flush(); }catch (IOException sio) { Console.WriteLine("Send: IO exception {0}", sio.Message); } try { MemoryStream ms = new MemoryStream(); byte[] buffer = new byte[1024]; do { ms.Write(buffer, 0, client.Read(buffer, 0, buffer.Length)); } while (!client.IsMessageComplete); string stringData = Encoding.UTF8.GetString(ms.ToArray()); CommandSerializers.WriteGreen("Client received RESPONSE: De-Serialized as: {0}\n", stringData); ProcessCommandC(stringData); }catch (IOException sio) { Console.WriteLine("Receive: IO exception {0}", sio.Message); } } } }
public void WriteToClientStream(NamedPipeClientStream stream, bool flush) { var bytes = ToBytes(); lock (stream) { stream.Write(bytes, 0, bytes.Length); if (flush) { stream.Flush(); } } }
public void Send(byte[] msg) { using (var _namedPipeClient = new NamedPipeClientStream(".", _settings.Udf2ProxyNamedPipeName, PipeDirection.Out, PipeOptions.None)) { if (!_namedPipeClient.IsConnected) { _namedPipeClient.Connect(); } _namedPipeClient.Write(msg, 0, msg.Length); _namedPipeClient.Flush(); _namedPipeClient.WaitForPipeDrain(); } }
/// <summary> /// Disconnects from the application /// </summary> public void Disconnect() { if (_pipe != null) { try { _pipe.Flush(); } catch { // ignored } try { _pipe.Close(); } catch { // ignored } _pipe = null; } }
private void AsyncSend(IAsyncResult asyncResult) { try { NamedPipeClientStream pipeStream = (NamedPipeClientStream)asyncResult.AsyncState; pipeStream.EndWrite(asyncResult); pipeStream.Flush(); pipeStream.Close(); pipeStream.Dispose(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
protected void OnWrite(IAsyncResult iarIn) { try { // Get the pipe. NamedPipeClientStream pipeClientLocal = (NamedPipeClientStream)iarIn.AsyncState; // End the write. pipeClientLocal.EndWrite(iarIn); pipeClientLocal.Flush(); pipeClientLocal.Close(); pipeClientLocal.Dispose(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private void AsyncSend(IAsyncResult iar) { try { NamedPipeClientStream pipeStream = (NamedPipeClientStream)iar.AsyncState; // Get the pipe pipeStream.EndWrite(iar); // End the write pipeStream.Flush(); pipeStream.Close(); pipeStream.Dispose(); } catch (Exception oEX) { ServiceLog.WriteLog("[Service] Intercomms Client AsyncSend Error," + oEX.Message); } }
public bool SendPacket(ActionPacket packet) { using (var client = new NamedPipeClientStream("USBHelperLauncher")) { client.Connect(); DataStream ds = new DataStream(client); XDocument doc = packet.Serialize(); byte[] bytes = Encoding.UTF8.GetBytes(doc.ToString()); ds.WriteByteArray(bytes, CompressionLevel.Fastest); client.Flush(); byte result = (byte)client.ReadByte(); client.Close(); return(BitConverter.ToBoolean(new byte[] { result }, 0)); } }
/// <summary> /// Stop the client and disconnect from the server /// </summary> /// <param name="theSendMessage">Send a disconnection message to the server? If false, we were probably kicked, etc.</param> public void Stop(bool theSendMessage = true) { if (itsIsStopping) { return; } if (theSendMessage) { PipeMessageUserDisconnection aMessageUserDisconnection = new PipeMessageUserDisconnection(Username); Send(aMessageUserDisconnection); } itsIsStopping = true; itsPipeClient.Flush(); itsPipeClient.Close(); }
public static int Write(this NamedPipeClientStream stream, string str) { var buffer = Encoding.Unicode.GetBytes(str); var len = buffer.Length; if (len > UInt16.MaxValue) { len = (int)UInt16.MaxValue; } stream.WriteByte((byte)(len / 256)); stream.WriteByte((byte)(len & 255)); stream.Write(buffer, 0, len); stream.Flush(); return(buffer.Length + 2); }
public static IWebHost CreateWebHost() { var webHostBuilder = new WebHostBuilder() .UseLoggerFactory(_loggerFactory) .UseConfiguration(Configuration) .UseKestrel(options => { //options.UseConnectionLogging(); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>(); var webHost = webHostBuilder.Build(); var serverAddresses = webHost.ServerFeatures.Get <IServerAddressesFeature>(); string pipeName = _startupOptions.WriteServerUrlsToPipe; if (pipeName != null) { NamedPipeClientStream pipe; try { pipe = new NamedPipeClientStream(".", pipeName, PipeDirection.Out); pipe.Connect(10000); } catch (IOException ex) { _logger.LogCritical(0, ex, $"Requested to write server.urls to pipe '{pipeName}', but it is not a valid pipe handle."); throw; } catch (TimeoutException ex) { _logger.LogCritical(0, ex, $"Requested to write server.urls to pipe '{pipeName}', but timed out while trying to connect to pipe."); throw; } var applicationLifetime = webHost.Services.GetService <IApplicationLifetime>(); applicationLifetime.ApplicationStarted.Register(() => Task.Run(() => { using (pipe) { string serverUriStr = JsonConvert.SerializeObject(serverAddresses.Addresses); _logger.LogTrace($"Writing server.urls to pipe '{pipeName}':{Environment.NewLine}{serverUriStr}"); var serverUriData = Encoding.UTF8.GetBytes(serverUriStr); pipe.Write(serverUriData, 0, serverUriData.Length); pipe.Flush(); } _logger.LogTrace($"Wrote server.urls to pipe '{pipeName}'."); })); } return(webHost); }
private static void SendDataByPipe(String data) { bool connectFlag = true; string connectErrMsg = ""; string title = ""; using (NamedPipeClientStream pipeSend = new NamedPipeClientStream( "localhost", CommonString.PipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None)) { try { pipeSend.Connect(300); byte[] bytesRead = new byte[1024]; int length = pipeSend.Read(bytesRead, 0, 1024); title = Encoding.Default.GetString(bytesRead, 0, length); bool searchFlag = ((!exitCall) && (data.Length <= sendDataMaxLength)); string strSend = string.Format("{0}{1}{2}", exitCall ? "1" : "0", searchFlag ? "1" : "0", searchFlag ? data : ""); byte[] bytes = Encoding.Default.GetBytes(strSend); pipeSend.Write(bytes, 0, bytes.Length); pipeSend.Flush(); } catch (Exception ex) { connectFlag = false; connectErrMsg = ex.Message; } } if (!exitCall) { if (!connectFlag) { MessageBox.Show(string.Format( "搜索 {0} 失败\n{1}!", data, connectErrMsg)); } else if (data.Length > sendDataMaxLength) { MessageBox.Show(string.Format( "搜索的字符串\n{0}\n长度为 {1}\n超过 50 !", data, data.Length), title); } } }
private void AsyncSend(IAsyncResult iAsyncResult) { try { NamedPipeClientStream pipeStream = (NamedPipeClientStream)iAsyncResult.AsyncState; pipeStream.EndWrite(iAsyncResult); pipeStream.Flush(); pipeStream.Close(); pipeStream.Dispose(); } catch (Exception exception) { } }
public static void AsynSendCallBack(IAsyncResult iar) { try { Console.WriteLine("[Client] Non sono riuscito a connettermi..."); NamedPipeClientStream pipeClient = (NamedPipeClientStream)iar.AsyncState; pipeClient.EndWrite(iar); pipeClient.Flush(); pipeClient.Close(); pipeClient.Dispose(); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
private void Write(Opcode opcode, string data) { if (IsDisposed) { throw new DiscordException("Disposed"); } Utils.Log($"Write: {opcode}; {data}"); var result = Fit((int)(1.5 * data.Length + 8)); var length = _encoding.GetBytes(data, 0, data.Length, result, 8); GetBytes((int)opcode, result, 0); GetBytes(length, result, 1); _pipe.Write(result, 0, length + 8); _pipe.Flush(); }
private static void ExecuteCommand(NamedPipeClientStream pipe, string command) { if (string.IsNullOrEmpty(command)) { return; } byte[] bytes = Encoding.Default.GetBytes(command); pipe.Write(bytes, 0, bytes.Length); pipe.Flush(); var result = ReadMessage(pipe); Console.WriteLine(Encoding.UTF8.GetString(result)); Console.WriteLine(); }
private void AsyncSend(IAsyncResult iar) { try { NamedPipeClientStream pipeStream = (NamedPipeClientStream)iar.AsyncState; pipeStream.EndWrite(iar); pipeStream.Flush(); pipeStream.Close(); pipeStream.Dispose(); } catch (Exception except) { throw new SystemException(except.Message); } }
private void AsyncSend(IAsyncResult iar) { try { NamedPipeClientStream pipeStream = (NamedPipeClientStream)iar.AsyncState; pipeStream.EndWrite(iar); pipeStream.Flush(); pipeStream.Close(); pipeStream.Dispose(); } catch (Exception oEX) { Debug.WriteLine(oEX.Message); } }
public void WriteMessage(string message) { log.LogVerbose($"Post message to cmake server:{Environment.NewLine}" + $"{message}"); string completeMessage = StartTag + message + EndTag; byte[] outBuffer = streamEncoding.GetBytes(completeMessage); int len = outBuffer.Length; if (len > ushort.MaxValue) { len = ushort.MaxValue; } ioStream.Write(outBuffer, 0, len); ioStream.Flush(); }
public Task <MessageBridgeResponse> RequestAsync(MessageBridgeRequest request) { return(Task.Run(() => { var pipe = new NamedPipeClientStream(_pipeName); try { pipe.Connect(); pipe.ReadMode = PipeTransmissionMode.Message; var buff = Encoding.UTF8.GetBytes(request.ToJson()); pipe.Write(buff, 0, buff.Length); pipe.Flush(); pipe.WaitForPipeDrain(); buff = new byte[BUFFER_SIZE]; var ms = new MemoryStream(); do { ms.Write(buff, 0, pipe.Read(buff, 0, buff.Length)); }while (!pipe.IsMessageComplete); var json = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); ms.Dispose(); buff = null; if (string.IsNullOrEmpty(json)) { return MessageBridgeResponse.CreateFailureResponse("No content."); } pipe.Close(); pipe.Dispose(); return MessageBridgeResponse.CreateSuccessResponse(json); } catch (Exception ex) { return MessageBridgeResponse.CreateFailureResponse(ex.Message); } })); }
public static void ClientPInvokeChecks() { using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.In)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.Out)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); Assert.False(client.CanRead); Assert.False(client.CanSeek); Assert.False(client.CanTimeout); Assert.True(client.CanWrite); Assert.False(client.IsAsync); Assert.True(client.IsConnected); Assert.Equal(0, client.OutBufferSize); Assert.Equal(PipeTransmissionMode.Byte, client.ReadMode); Assert.NotNull(client.SafePipeHandle); Assert.Equal(PipeTransmissionMode.Byte, client.TransmissionMode); client.Write(new byte[] { 123 }, 0, 1); client.WriteAsync(new byte[] { 124 }, 0, 1).Wait(); client.WaitForPipeDrain(); client.Flush(); serverTask.Wait(); } } using (NamedPipeServerStream server = new NamedPipeServerStream("foo", PipeDirection.Out)) { using (NamedPipeClientStream client = new NamedPipeClientStream(".", "foo", PipeDirection.In)) { Task serverTask = DoServerOperationsAsync(server); client.Connect(); Assert.Equal(0, client.InBufferSize); byte[] readData = new byte[] { 0, 1 }; Assert.Equal(1, client.Read(readData, 0, 1)); Assert.Equal(1, client.ReadAsync(readData, 1, 1).Result); Assert.Equal(123, readData[0]); Assert.Equal(124, readData[1]); serverTask.Wait(); } } }
public void Write(byte[] bufferIn, bool waitSync) { try { NamedPipeClientStream pipeClientLocal = new NamedPipeClientStream( ".", SimplePipePeer.FormatPipeName(this.pipeName, !this.client), PipeDirection.InOut, PipeOptions.Asynchronous ); // The connect function will indefinitely wait for the pipe to become available.\ // TODO: Is this thread-safe? I don't think it is. int localTimeoutCountdown = 0; do { try { pipeClientLocal.Connect(1000); this.connected = true; } catch (IOException ex) { localTimeoutCountdown++; if (0 <= this.ConnectionTimeout && this.ConnectionTimeout <= localTimeoutCountdown) { throw new TimeoutException(ex.Message); } } } while(!this.connected); if (waitSync) { pipeClientLocal.Write(bufferIn, 0, bufferIn.Length); pipeClientLocal.Flush(); pipeClientLocal.Close(); pipeClientLocal.Dispose(); } else { // Just kick off the process and finish it below. pipeClientLocal.BeginWrite(bufferIn, 0, bufferIn.Length, new AsyncCallback(this.OnWrite), pipeClientLocal); } } catch (TimeoutException ex) { // TODO: Does this still execute finally{} below? throw ex; } finally { this.connected = false; } }
public static async Task ServerDisconnectedPipeThrows() { using (NamedPipeServerStream server = new NamedPipeServerStream("testServer3", PipeDirection.In)) using (NamedPipeClientStream client = new NamedPipeClientStream(".", "testServer3", 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); server.Dispose(); Assert.Throws<IOException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => client.WriteByte(123)); Assert.Throws<IOException>(() => client.Flush()); } 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("testServer3", PipeDirection.InOut)) using (NamedPipeClientStream client = new NamedPipeClientStream("testServer3")) { byte[] buffer = new byte[] { 0, 0, 0, 0 }; Task clientConnect1 = client.ConnectAsync(); server.WaitForConnection(); await clientConnect1; Assert.True(client.IsConnected); Assert.True(server.IsConnected); server.Dispose(); Assert.Throws<IOException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => client.WriteByte(123)); Assert.Throws<IOException>(() => client.Flush()); int length = client.Read(buffer, 0, buffer.Length); Assert.Equal(0, length); int byt = client.ReadByte(); } } }