У меня есть служба Windows, а клиент слушает со следующим funcionality:Использование именованных каналов, как писать сообщения, клиент получает по очереди один за другим?
Win службы:
- Создает именованный канал
- Создает процесс клиента
- Уэйтс для подключения
- Записывает клиенту процесс
- Читает от клиента
- Записывает клиенту pr ocess
- Читает от клиента
...
public static bool StartProcessAsCurrentUser() { var hUserToken = IntPtr.Zero; var sInfo = new STARTUPINFO(); var procInfo = new PROCESS_INFORMATION(); var pEnv = IntPtr.Zero; int iResultOfCreateProcessAsUser; string cmdLine = "ClientNamedPipeForm.exe"; sInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO)); byte[] buffer = new byte[BUFSIZE]; try { var tSecurity = new SECURITY_ATTRIBUTES(); tSecurity.nLength = Marshal.SizeOf(tSecurity); var pSecurity = new SECURITY_ATTRIBUTES(); pSecurity.nLength = Marshal.SizeOf(pSecurity); pSecurity.bInheritHandle = true; //For controling handles from child process IntPtr pointer = Marshal.AllocHGlobal(Marshal.SizeOf(pSecurity)); Marshal.StructureToPtr(pSecurity, pointer, true); PipeSecurity ps = new PipeSecurity(); System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow); ps.AddAccessRule(par); NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.WriteThrough, 10, 10, ps); StreamWriter sw = new StreamWriter(pipeServer); if (!CreateProcessAsUser(hUserToken, null, // Application Name cmdLine, // Command Line IntPtr.Zero, IntPtr.Zero, true, dwCreationFlags, pEnv, null, // Working directory ref sInfo, out procInfo)) { throw new Exception("StartProcessAsCurrentUser: CreateProcessAsUser failed.\n"); } try { pipeServer.WaitForConnection(); sw.WriteLine("Waiting"); sw.Flush(); pipeServer.WaitForPipeDrain(); Thread.Sleep(5000); sw.WriteLine("Waiting2"); sw.Flush(); pipeServer.WaitForPipeDrain(); Thread.Sleep(5000); sw.WriteLine("Waiting32"); sw.Flush(); pipeServer.WaitForPipeDrain(); Thread.Sleep(5000); sw.WriteLine("QUIT"); sw.Flush(); pipeServer.WaitForPipeDrain(); } catch (Exception ex) { throw ex; } finally { if (pipeServer.IsConnected) { pipeServer.Disconnect(); } } } finally { //Closing things } return true; }
Клиент:
- Создает именованный канал
- Подключается
- Считывает из службы
- Пишет в форме
- Пишет обслуживать
- Считывает из службы
- Пишет в форме
- Пишет обслуживать
...
private void Client() { try { IntPtr hPipe; string dwWritten; byte[] buffer = new byte[BUFSIZE]; NamedPipeClientStream pipeClient = new NamedPipeClientStream(".","testpipe", PipeDirection.In, PipeOptions.WriteThrough); if (pipeClient.IsConnected != true) { pipeClient.Connect(); } StreamReader sr = new StreamReader(pipeClient); string temp; bool cont = true; while (cont) { temp = ""; temp = sr.ReadLine(); if (temp != null) { listBox1.Items.Add(temp); listBox1.Refresh(); } if (temp != "QUIT") { sw.WriteLine("Response"); sw.Flush(); pipeClient.WaitForPipeDrain(); } else { sw.WriteLine("Response"); cont = false; } } } catch (Exception ex) { throw new Exception("Exception: " + ex.Message); }
появляется проблема написав до listbox1
. Форма (и ее listbox1
) появляется только на экране пользователя, когда весь процесс закончился, и он отображает сразу четыре сообщения. У меня есть Thread.Sleep(5000)
на стороне обслуживания, чтобы показать, что каждое сообщение написано отдельно, но я не уверен, что процесс не дождался Thread
, и я его неправильно тестирую, или форма отображается со всеми сообщениями по какой-то причине ...
спасибо миллиона. Великий псевдокод :). – AdSsa