void OnApplicationQuit() { UnityEngine.Debug.Log("Client disconnected."); server.Close(); server.Dispose(); StopCoroutine("manage_data"); }
public static void commandThread() { Logger.WriteLine("[Scanner.commandThread] Ожидание подключения", LogLevel.WARN); commandPipe.WaitForConnection(); commandReader = new BinaryReader(commandPipe, Configuration.PipeEncoding); Logger.WriteLine("[Scanner.commandThread] Подключено", LogLevel.OK); while (true) { var code = commandReader.ReadByte(); switch (code) { case 0: { Logger.WriteLine("[Scanner.commandThread] Очистка буфера задач сканирования", LogLevel.WARN); lock (ScanTasks.TaskQueue.SyncRoot) { ScanTasks.TaskQueue.Clear(); ScanTasks.ActiveScanTasks = 0; } break; } case 1: { Logger.WriteLine("[Scanner.commandThread] Очистка буфера задач сканирования", LogLevel.WARN); lock (ScanTasks.TaskQueue.SyncRoot) { ScanTasks.TaskQueue.Clear(); ScanTasks.ActiveScanTasks = 0; } for (int index = 0; index < ScanTasks.ScanThreads.Length; index++) { Logger.WriteLine($"[Scanner.commandThread] Остановка потока сканирования {index}", LogLevel.WARN); ScanTasks.ScanThreads[index].Abort(); } Logger.WriteLine("[Scanner.commandThread] Остановка потоков", LogLevel.WARN); inputHandler.Abort(); signatureHandler.Abort(); Thread.Sleep(100); Logger.WriteLine("[Scanner.commandThread] Закрытие труб", LogLevel.WARN); commandPipe.Close(); inputPipe.Close(); commandPipe.Close(); outputPipe.Close(); commandHandler.Abort(); break; } } } }
internal override void Close() { stopEvent.Set(); if (PipeServerStream != null) { try { PipeServerStream.Close(); PipeServerStream.Dispose(); } catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.Message); } PipeServerStream = null; } if (pipeThread != null) { pipeThread.Join(); pipeThread = null; } }
private void Start() { _tokenSource = new CancellationTokenSource(); _ct = _tokenSource.Token; _serverTask = Task.Run(() => { // Were we already canceled? _ct.ThrowIfCancellationRequested(); InitServer(); while (true) { Update(); // Poll on this property if you have to do // other cleanup before throwing. if (_ct.IsCancellationRequested) { _server?.Close(); _server?.Dispose(); _ct.ThrowIfCancellationRequested(); } Task.Delay(200).Wait(); } }, _tokenSource.Token); }
private void WaitForConnectionCallBack(IAsyncResult result) { try { _pipeServer.EndWaitForConnection(result); } catch (ObjectDisposedException) { return; } try { var sentMessage = _serializer.DeserializeFromStream <NamedPipeMessage>(_pipeServer); if (sentMessage != null) { _messages.Add(sentMessage); } } finally { try { _pipeServer.Close(); } // ReSharper disable once EmptyGeneralCatchClause catch { } StartNewPipeServer(); } }
public void StopCPPPlayer() { try { pipeStream.WaitForConnection(); using (StreamReader sr = new StreamReader(pipeStream)) { string line; while ((line = sr.ReadLine()) != null) { Thread.Sleep(500); string strValue = line; if (line == "-1000") { break; } } } CoreEvent.SetEvent(m_handle); pipeStream.Close(); CoreEvent.CloseHandle(m_handle); } catch (Exception es) { return; } }
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { //goon = false; //Console.WriteLine("Stopping .... "); //producerThread.Join(); //Console.WriteLine("Stopped .... "); if (Pipe_Started) { if (server != null) { server.Close(); server.Dispose(); server = null; } producerThread.Abort(); } //if (server != null) //{ // server.Close(); // server.Dispose(); // server = null; //} //Application.Exit(); }
private async void Run() { var pipeServer = new NamedPipeServerStream($"BuildNotifications.DummyBuildServer.{_port}", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); try { await pipeServer.WaitForConnectionAsync(_cancelToken.Token); } catch (Exception) { pipeServer.Close(); return; } _buildNotificationsProcessHook.SearchForProcess(); pipeServer.ReadMode = PipeTransmissionMode.Byte; var buffer = new byte[Constants.Connection.BufferSize]; while (IsRunning) { Debug.WriteLine("S Receiving data..."); var bufferLength = pipeServer.Read(buffer, 0, Constants.Connection.BufferSize); Debug.WriteLine($"S Received {bufferLength} bytes"); var command = Encoding.ASCII.GetString(buffer, 0, bufferLength); _parser.ParseCommand(command, pipeServer); Thread.Sleep(10); } pipeServer.Close(); }
/// <summary> /// Stop method implementation /// </summary> public void Stop() { try { MustExit = true; if (ConfigPipeServer != null) { ConfigPipeServer.WaitForPipeDrain(); ConfigPipeServer.Disconnect(); } } catch (Exception ex) { LogForSlots.WriteEntry("PipeServer Stop Error : " + ex.Message, EventLogEntryType.Error, 8888); if (ConfigPipeServer != null) { ConfigPipeServer.Close(); } } finally { if (ConfigPipeServer != null) { ConfigPipeServer.Close(); ConfigPipeServer.Dispose(); } ConfigPipeServer = null; } }
private void Listen() { if (cancellationToken.IsCancellationRequested) { pipeStream.Close(); return; } byte[] pBuffer = new byte[BufferSize]; pipeStream.ReadAsync(pBuffer, 0, BufferSize, cancellationToken.Token).ContinueWith(t => { int ReadLen = t.Result; if (ReadLen == 0) { OnPipeClientClosed.Invoke(this, null); cancellationToken.Cancel(); pipeStream.Close(); return; } Listen(); OnMessageRecieved.Invoke(Encoding.UTF8.GetString(pBuffer, 0, ReadLen)); }); }
public void Close() { if (connectState != ConnectState.notBornYet && connectState != ConnectState.dead) {//開いてないパイプや閉じた閉じると例外?, 壊れた(切断)パイプ閉じると例外は来ないが謎の待ち時間が発生して怖い pipeS.Close(); connectState = ConnectState.dead; } }
public void Stop() { working = false; server.WaitForPipeDrain(); server.Disconnect(); server.Close(); server.Dispose(); }
public void Connect() { try { if (_connected) { return; } do { try { //at server clientPipeRead->_pipeClientWrite var ps = new PipeSecurity(); ps.AddAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.FullControl, System.Security.AccessControl.AccessControlType.Allow)); if (_pipeClientWrite != null) { _pipeClientWrite.Close(); } //_pipeClientWrite.Dispose(); _pipeClientWrite = new NamedPipeServerStream("clientPipeRead", PipeDirection.InOut, 10, PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, ps); //if (_pipeServerWrite == null) // _pipeServerWrite = new NamedPipeServerStream("opcPipeRead", PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, ps); _pipeClientWrite.WaitForConnection(); _ssWrite = new StreamString(_pipeClientWrite); if (_pipeClientRead != null) { _pipeClientRead.Close(); } //_pipeClientRead.Dispose(); _pipeClientRead = new NamedPipeServerStream("clientPipeWrite", PipeDirection.InOut, 10, PipeTransmissionMode.Message, PipeOptions.WriteThrough, 1024, 1024, ps); _pipeClientRead.WaitForConnection(); _ssRead = new StreamString(_pipeClientRead); _connected = true; return; } catch (Exception ex) { if (ex.Message.Contains("The network path was not found")) { Thread.Sleep(TimeSleep); //wait for new connection } else { throw new Exception(ex.Message); } } } while (!_connected); } catch (Exception ex) { File.AppendAllText(_pathLog, "\r\n" + DateTime.Now.ToString() + ", ClientWinsService: " + ex.ToString()); } }
public static void UpdateMonitor() { Process.Start("NewMesMonitor.exe"); NamedPipeServerStream pipeServer = new NamedPipeServerStream("monitorpipe", PipeDirection.InOut, 1); // Wait for a client to connect pipeServer.WaitForConnection(); // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. ss.WriteString("Validating server"); while (Thread.CurrentThread.IsAlive) { string currentMonitorMessage = ""; foreach (ChatData chatData in chats) { if (chatData.CountNewMes == 0) { currentMonitorMessage += "There is no new messages with " + chatData.UserName + "\n"; } else { currentMonitorMessage += "There is " + chatData.CountNewMes + " new messages with " + chatData.UserName + "\n"; } } try { ss.WriteString(currentMonitorMessage); } catch (Exception e) { pipeServer.Close(); new Thread(UpdateMonitor) { IsBackground = true }.Start(); Thread.CurrentThread.Abort(); } Thread.Sleep(1000); } ss.WriteString("Close"); pipeServer.Close(); }
public void Disconnect() { if (isConnected) { isConnected = false; TurnOff(); pipe.Close(); pipe.Dispose(); } }
private void onRead(IAsyncResult ar) { NamedPipeServerStream cNamedPipeServer = ar.AsyncState as NamedPipeServerStream; try { int iNumBytes = cNamedPipeServer.EndRead(ar); if (iNumBytes == 0) { cNamedPipeServer.Close(); cNamedPipeServer.Dispose(); Listen(); } else { if (iNumBytes < MAX_BUFFER_SIZE) { byte[] bData = __cBuffer; if (__cMemStream.Position > 0) { __cMemStream.Write(__cBuffer, 0, iNumBytes); bData = __cMemStream.GetBuffer(); iNumBytes = (int)__cMemStream.Position; __cMemStream.Position = 0; } string sText = Encoding.UTF8.GetString(bData, 0, iNumBytes); if (onMessage != null) { onMessage(this, new MessageEvent() { Buffer = bData, Length = iNumBytes, Message = sText }); } } else { __cMemStream.Write(__cBuffer, 0, iNumBytes); } cNamedPipeServer.BeginRead(__cBuffer, 0, MAX_BUFFER_SIZE, onRead, cNamedPipeServer); } } catch (Exception __errExcep) { if (logger.IsErrorEnabled) { logger.ErrorFormat("{0}\r\n{1}", __errExcep.Message, __errExcep.StackTrace); } cNamedPipeServer.Close(); cNamedPipeServer.Dispose(); } }
public void UnInit() { lock (pipeServerLock) { if (pipeServer != null) { pipeServer.Close(); pipeServer = null; } } }
public void StartPipeListener() { //do not start more than 1 task. if (!new TaskStatus?[] { TaskStatus.RanToCompletion, TaskStatus.Faulted, TaskStatus.WaitingForChildrenToComplete, null }.Contains(listenertask?.Status)) { return; } listenertask = Task.Run(() => { while (true) { try { var aresetev = new AutoResetEvent(false); var stream = new NamedPipeServerStream("NowPlayingTunesV2PIPE", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); stream.BeginWaitForConnection((IAsyncResult ar) => { if (stopevent.WaitOne(0)) { //WaitOne(0) returns true when state is set taskstopwait.Set(); return; } stream.EndWaitForConnection(ar); if (!stream.IsConnected) { return; } var memstream = new MemoryStream(); int readret = -1; while (readret != 0) { var buffer = new byte[1024]; readret = stream.Read(buffer, 0, buffer.Length); memstream.Write(buffer, 0, readret); } stream.Close(); aresetev.Set(); var bary = memstream.ToArray(); var rawjson = System.Text.Encoding.UTF8.GetString(bary); var sinfo = JsonConvert.DeserializeObject <SongInfo>(rawjson); LastPlayedSong = sinfo; OnMusicPlay(sinfo); }, null); if (WaitHandle.WaitAny(new WaitHandle[] { aresetev, stopevent }) == 1) { stream.Close(); return; } } catch { } } }); }
public void TransmitThread() { _npServer?.Close(); _npServer = new NamedPipeServerStream(PipeName); _npServer.WaitForConnection(); Transmit(); _npServer.Close(); _npServer?.Dispose(); }
void ServerListen() { var ps = new PipeSecurity(); System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.BuiltinUsersSid, null); ps.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow)); while (true) { NamedPipeServerStream pipe = null; try { pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024, ps); pipe.WaitForConnection(); Thread clientConnectionHandler = new Thread(new ParameterizedThreadStart(HandleClientConnection)) { IsBackground = true }; clientConnectionHandler.Start(pipe); if (!clientConnectionHandler.Join(1000)) { clientConnectionHandler.Abort(); Console.WriteLine("Connection handler timeout reached"); Logger.Instance.WriteLine("Client connection handler timed out in item server thread..."); } pipe.Close(); } catch (UnauthorizedAccessException e) { // note: should only come here if another pipe with same name is already open (= another instance of d2interface is running) Logger.Instance.WriteLine("Error: {0}", e.Message); Thread.Sleep(1000); // try again in 1 sec to prevent tool from lagging } catch (IOException e) { Logger.Instance.WriteLine("ItemServer Error: {0}", e.Message); if (pipe != null) { pipe.Close(); } } catch (Exception e) { Console.WriteLine(e.Message); Logger.Instance.WriteLine("Other exception: {0}", e.Message); } } }
static void WaitForClientConnection(IAsyncResult result) { PipeInfo pipeInfo = (PipeInfo)result.AsyncState; NamedPipeServerStream pipeServer = (NamedPipeServerStream)pipeInfo.Stream; int ret = pipeInfo.OnClientConnect != null ? WAIT_FOR_NEXT_CONNECTION : CLOSE_PIPE; // End waiting for the connection try { pipeServer.EndWaitForConnection(result); //do delegate function here if (pipeInfo.OnClientConnect != null && pipeServer.IsConnected) { ret = pipeInfo.OnClientConnect(pipeInfo); } } catch (Exception) { ret = CLOSE_PIPE; } switch (ret) { case CLOSE_PIPE: pipeServer.Close(); pipeServer.Dispose(); pipeServer = null; break; case WAIT_FOR_NEXT_CONNECTION: if (pipeServer.IsConnected) { try { pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForClientConnection), pipeInfo); } catch (IOException) { pipeServer = Create(pipeInfo.Name, pipeInfo.Direction, pipeInfo.Security, pipeInfo.OnClientConnect); } } else { pipeServer.Close(); pipeServer.Dispose(); pipeServer = null; pipeServer = Create(pipeInfo.Name, pipeInfo.Direction, pipeInfo.Security, pipeInfo.OnClientConnect); } break; } //end switch }
//=================================================================== // 多重起動防止 //=================================================================== /// NamedPipeServerStreamを生成する private void StartPipeServer(SynchronizationContext context) { Debug.WriteLine("[OPEN]", "NamedPipe"); var pipe = new NamedPipeServerStream(App.namedPipeName, PipeDirection.In, -1, PipeTransmissionMode.Message, PipeOptions.Asynchronous); try { pipe.BeginWaitForConnection((result) => { try { pipe.EndWaitForConnection(result); // 新しいPipeを生成 this.StartPipeServer(context); // Read var data = new byte[1024]; // 260文字(MAX_PATH)x3byte、改行とオプション分 pipe.BeginRead(data, 0, data.Length, (readResult) => { var args = new CommandLineArgs(); try { var actualLength = pipe.EndRead(readResult); args = new CommandLineArgs(data, actualLength); } catch { // 出来なければできないでOK Debug.WriteLine("Read named pipe failed", "App.StartPipeServer"); return; } finally { pipe.Close(); } Debug.WriteLine("CLI feature requested:"); context.Post((state) => { if (args.ProfilePathOption) { App.Impl.OpenProfile(args.ProfilePath); } this.ParseAndRun(args, true); }, null); Debug.WriteLine("[CLOSE]", "NamedPipe"); }, null); } catch { // 出来なければできないでOK Debug.WriteLine("Connect named pipe failed", "App.StartPipeServer"); pipe.Close(); } }, null); } catch { // 出来なければできないでOK Debug.WriteLine("Start named pipe failed", "App.StartPipeServer"); pipe.Close(); } }
private static void Server1(string pipename, decimal max_loop) { // Open the named pipe. var server = new NamedPipeServerStream(pipename); try { Console.WriteLine("Waiting for connection..."); server.WaitForConnection(); Console.WriteLine("Connected."); } catch { server.Close(); server.Dispose(); } var bw = new BinaryWriter(server); int counter = 0; Random cRand = new System.Random(); while (true) { try { int[] arrayNum = new int[45]; for (int i = 0; i < arrayNum.Length; i++) { arrayNum[i] = cRand.Next(i); } var str = string.Join(",", arrayNum); //'.' + var buf = Encoding.ASCII.GetBytes(str + "\r\n"); // Get ASCII byte array //bw.Write((uint)buf.Length); // Write string length bw.Write(buf); // Write string Console.WriteLine("Wrote:{0:D2} {1}", counter + 1, str); counter++; if (counter > max_loop - 1) { break; } } catch (EndOfStreamException) { break; // When client disconnects } } Console.WriteLine("Client disconnected."); server.Close(); server.Dispose(); }
public bool End() { try { pipeServer.Close(); pipeServer.Dispose(); pipeServer = null; return(true); } catch (Exception ex) { OnError(NamedPipeListenerErrorType.CloseAndDisposePipe, ex); return(false); } }
private static void ServerThread(object data) { NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName, PipeDirection.InOut, NumThreads); int threadId = Thread.CurrentThread.ManagedThreadId; // Wait for a client to connect pipeServer.WaitForConnection(); try { // Read the request from the client. Once the client has // written to the pipe its security token will be available. StreamString ss = new StreamString(pipeServer); string filename = ss.ReadString(); Utils fileReader = new Utils(); pipeServer.RunAsClient(fileReader.Start); // Catch the IOException that is raised if the pipe is broken // or disconnected. } catch {} finally { pipeServer.Close(); } }
private void PipeLoop() { try { var security = new PipeSecurity(); var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); security.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.FullControl, AccessControlType.Allow)); while (Running) { var namedPipeServerStream = new NamedPipeServerStream(_pipeName, PipeDirection.In, 254, PipeTransmissionMode.Byte, PipeOptions.None, 254, 254, security); namedPipeServerStream.WaitForConnection(); var buffer = new byte[254]; namedPipeServerStream.Read(buffer, 0, 254); namedPipeServerStream.Close(); var task = new Task(() => HandleMessage(buffer)); task.Start(); } } catch { // ignored } }
public override void Close() { if (stream != null) { stream.Close(); } }
private void ReadThreadStart() { try { // wait for decoder to start writing while (!_dataWriteStarted || !_decoderIsRunning || !_encoderIsRunning) { Thread.Sleep(100); } var buffer = new byte[0xA00000]; // 10 MB var read = 0; do { if (_decoderIsRunning) { read = DecodeProcess.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length); } if (_encoderIsRunning) { _encodePipe.Write(buffer, 0, read); } } while (read > 0 && _decoderIsRunning && _encoderIsRunning); _encodePipe.Close(); } catch (Exception exc) { Log.Error(exc); } }
protected void OnConnection(IAsyncResult iarIn) { this.connected = true; NamedPipeServerStream pipeServerLocal = (NamedPipeServerStream)iarIn.AsyncState; pipeServerLocal.EndWaitForConnection(iarIn); // Read the message and execute the callback on it. byte[] buffer = new byte[BUFFER_SIZE]; pipeServerLocal.Read(buffer, 0, buffer.Length); this.OnRead(Encoding.UTF8.GetString(buffer)); pipeServerLocal.Close(); this.connected = false; if (!this.active) { // Don't continue listening. return; } // Create a new recursive wait server. pipeServerLocal = CreateServerPipe( SimplePipePeer.FormatPipeName(this.pipeName, this.client) ); pipeServerLocal.BeginWaitForConnection(new AsyncCallback(this.OnConnection), pipeServerLocal); }
public void Close() { if (ioStream != null) { ioStream.Close(); } bClientConn = false; /* Wake up the write thread so it can die */ newWriteData.Set(); /* Close connection streams */ if (waitThread != null) { if (sStream != null) { sStream.Close(); } else if (cStream != null) { cStream.Close(); } } }