private PipeConnectionBlock connectTo(string serverPipeName) { var client = new NamedPipeClientStream(".", serverPipeName, PipeDirection.InOut, PipeOptions.Asynchronous); client.Connect(3000); if (client.IsConnected) { client.ReadMode = PipeTransmissionMode.Message; var data = new JObject() { ["ClientName"] = _pipName }.ToStringEx(Formatting.None); var block = new PipeConnectionBlock() { Stream = client, TargetName = serverPipeName, Reader = new StreamReader(client, Encoding.UTF8), Writer = new StreamWriter(client, Encoding.UTF8) }; block.Writer.WriteLine(data);; var thread = new Thread(() => { readData(block.Reader, block.Stream); }); block.Thread = thread; thread.Start(); if (!_pipeConnections.TryAdd(serverPipeName, block)) { block.Close(); } return(block); } else { return(null); } }
private async void endWaitForConnection(IAsyncResult ar) { var pipeServer = (NamedPipeServerStream)ar.AsyncState; pipeServer.EndWaitForConnection(ar); pipeServer.ReadMode = PipeTransmissionMode.Message; var block = new PipeConnectionBlock() { Stream = pipeServer, Reader = new StreamReader(pipeServer, Encoding.UTF8), Writer = new StreamWriter(pipeServer, Encoding.UTF8) //ClientName = clientName }; //using (var sr = new StreamReader(pipeServer, Encoding.UTF8)) { var clientInfoStr = await block.Reader.ReadLineAsync(); var json = JsonConvert.DeserializeObject <JObject>(clientInfoStr); var clientName = json.GetString("ClientName"); block.TargetName = clientName; if (!_pipeConnections.TryAdd(clientName, block)) { block.Close(); } var thread = new Thread(() => { readData(block.Reader, block.Stream); }); block.Thread = thread; thread.Start(); } beginwaitForConnection(); }