2 min to read
C# named pipe
named pipe ๐งท
์๋ก ๋ค๋ฅธ ๋ ํ๋ก์ธ์ค ๊ฐ ๋ฉ์์ง๋ ๋ฐ์ดํฐ๋ฅผ ์ฃผ๊ณ ๋ฐ์์ผํ ๋ ํ๋ก์ธ์ค ํต์ ์ ํด์ผํ๋ค.
๊ทธ ์ค C#์์ ์ ๊ณตํ๋ Namedpipe๋ฅผ ์ด์ฉํ์ฌ ํต์ ํ๋ ๋ฐฉ๋ฒ์ด๋ค.
Namedpipe
- ์ด๋ฆ์ ๊ฐ์ง PIPE๋ฅผ ํตํด ํ๋ก์ธ์ค ๊ฐ ๋จ๋ฐฉํฅ ํต์ ์ ์ง์ํ๋ค.
- PIPE ์ด๋ฆ๋ง ์๋ฉด ์๋ก ๋ค๋ฅธ ํ๋ก์ธ์ค๋ผ๋ฆฌ ํต์ ์ด ๊ฐ๋ฅํ๋ค.
- FIFO (First In First Out)๊ตฌ์กฐ์ด๋ค.
- read ๋๋ write ๋ง ๊ฐ๋ฅํ๋ค.
- ์๋ฐฉํฅ ํต์ ์ ์ํด์๋ reae pipe, write pipe ํ๋ ์ฉ ๋ง๋ค์ด์ผ ํ๋ค.
- NamedPipeControl
public class NamedPipeControl { private const int TIMEOUT = 10000; private string PipeName { get; set; } public NamedPipeServerStream PipeServerStream { get; set; } public NamedPipeClientStream PipeClientStream { get; set; } public NamedPipeControl(string name) { PipeName = name; } public async void ServerOpen() { PipeServerStream = new NamedPipeServerStream(PipeName); Console.WriteLine("Wait a client"); PipeServerStream.WaitForConnection(); Console.WriteLine("Connected."); while(PipeServerStream.IsConnected) { var read = new byte[4096]; await PipeServerStream.ReadAsync(read, 0, read.Length); var msg = Encoding.UTF8.GetString(read).TrimEnd('\0'); Console.WriteLine(msg); } } public void ClientOpen() { PipeClientStream = new NamedPipeClientStream(PipeName); PipeClientStream.Connect(TIMEOUT); } public async void Write(string msg) { var write = Encoding.UTF8.GetBytes(msg); await PipeClientStream.WriteAsync(write, 0, write.Length); PipeClientStream.Flush(); } }
- Server
static void Main(string[] args) { NamedPipeControl Server = new NamedPipeControl("chanos"); Server.ServerOpen(); Console.ReadLine(); }
- Client
static void Main(string[] args) { NamedPipeControl Client = new NamedPipeControl("chanos"); Client.ClientOpen(); while(true) { Client.Write(Console.ReadLine()); } }
- ๊ฒฐ๊ณผ