1
0
mirror of https://github.com/chylex/TweetDuck.git synced 2025-05-10 17:34:07 +02:00

Implement a duplex anonymous pipe in TweetLib.Communication

This commit is contained in:
chylex 2017-08-13 15:14:17 +02:00
parent b967b1288f
commit 92acb823a4
2 changed files with 90 additions and 0 deletions

View File

@ -0,0 +1,89 @@
using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;
namespace TweetLib.Communication{
public abstract class DuplexPipe : IDisposable{
public static Server CreateServer(){
return new Server();
}
public static Client CreateClient(string token){
int space = token.IndexOf(' ');
return new Client(token.Substring(0, space), token.Substring(space+1));
}
protected readonly PipeStream pipeIn;
protected readonly PipeStream pipeOut;
private readonly Thread readerThread;
private readonly StreamWriter writerStream;
public event EventHandler<PipeReadEventArgs> DataIn;
protected DuplexPipe(PipeStream pipeIn, PipeStream pipeOut){
this.pipeIn = pipeIn;
this.pipeOut = pipeOut;
this.readerThread = new Thread(ReaderThread){
IsBackground = true
};
this.readerThread.Start();
this.writerStream = new StreamWriter(this.pipeOut);
}
private void ReaderThread(){
using(StreamReader read = new StreamReader(pipeIn)){
string data;
while((data = read.ReadLine()) != null){
DataIn?.Invoke(this, new PipeReadEventArgs(data));
}
}
}
public void Write(string data){
writerStream.WriteLine(data);
writerStream.Flush();
}
public void Dispose(){
try{
readerThread.Abort();
}catch{
// /shrug
}
pipeIn.Dispose();
writerStream.Dispose();
}
public sealed class Server : DuplexPipe{
private AnonymousPipeServerStream ServerPipeIn => (AnonymousPipeServerStream)pipeIn;
private AnonymousPipeServerStream ServerPipeOut => (AnonymousPipeServerStream)pipeOut;
internal Server() : base(new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable), new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)){}
public string GenerateToken(){
return ServerPipeIn.GetClientHandleAsString()+" "+ServerPipeOut.GetClientHandleAsString();
}
public void DisposeToken(){
ServerPipeIn.DisposeLocalCopyOfClientHandle();
ServerPipeOut.DisposeLocalCopyOfClientHandle();
}
}
public sealed class Client : DuplexPipe{
internal Client(string handleOut, string handleIn) : base(new AnonymousPipeClientStream(PipeDirection.In, handleIn), new AnonymousPipeClientStream(PipeDirection.Out, handleOut)){}
}
public sealed class PipeReadEventArgs : EventArgs{
public string Data { get; }
internal PipeReadEventArgs(string data) => Data = data;
}
}
}

View File

@ -35,6 +35,7 @@
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<Compile Include="DuplexPipe.cs" />
<Compile Include="Utils\NativeMethods.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Comms.cs" />