Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- class Program
- {
- const uint PIPE_ACCESS_INBOUND = 0x00000001;
- const uint PIPE_TYPE_BYTE = 0x00000000;
- const uint PIPE_READMODE_BYTE = 0x00000000;
- const uint PIPE_WAIT = 0x00000000;
- const uint PIPE_UNLIMITED_INSTANCES = 255;
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern IntPtr CreateNamedPipeA(
- string lpName,
- uint dwOpenMode,
- uint dwPipeMode,
- uint nMaxInstances,
- uint nOutBufferSize,
- uint nInBufferSize,
- uint nDefaultTimeOut,
- IntPtr lpSecurityAttributes);
- [DllImport("kernel32.dll", SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool ConnectNamedPipe(IntPtr hNamedPipe, IntPtr lpOverlapped);
- [DllImport("kernel32.dll", SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool CloseHandle(IntPtr hObject);
- [DllImport("kernel32.dll", SetLastError = true)]
- [return: MarshalAs(UnmanagedType.Bool)]
- public static extern bool ReadFile(
- IntPtr hFile,
- byte[] lpBuffer,
- uint nNumberOfBytesToRead,
- out uint lpNumberOfBytesRead,
- IntPtr lpOverlapped);
- static void Main()
- {
- string pipeName = @"\\.\pipe\MyNamedPipe";
- IntPtr pipeHandle = CreateNamedPipeA(
- pipeName,
- PIPE_ACCESS_INBOUND,
- PIPE_TYPE_BYTE,
- PIPE_UNLIMITED_INSTANCES,
- 0, // Buffer size for output data
- 0, // Buffer size for input data
- 0, // Default timeout (0 means blocking)
- IntPtr.Zero);
- if (pipeHandle != IntPtr.Zero)
- {
- Console.WriteLine("Named pipe created successfully. Waiting for a client to connect...");
- // Wait for a client to connect
- bool connected = ConnectNamedPipe(pipeHandle, IntPtr.Zero);
- if (connected)
- {
- Console.WriteLine("Client connected.");
- // Continuously listen for data in a loop
- while (true)
- {
- byte[] buffer = new byte[1024]; // Adjust the buffer size as needed
- uint bytesRead;
- bool success = ReadFile(pipeHandle, buffer, (uint)buffer.Length, out bytesRead, IntPtr.Zero);
- if (success && bytesRead > 0)
- {
- string data = Encoding.ASCII.GetString(buffer, 0, (int)bytesRead);
- Console.WriteLine("Received data from the client: " + data);
- }
- else
- {
- // If no data or an error occurs, break the loop
- Console.WriteLine("No data received or an error occurred.");
- break;
- }
- }
- }
- else
- {
- Console.WriteLine("Failed to connect to client. Error code: " + Marshal.GetLastWin32Error());
- }
- // Close the named pipe when done
- CloseHandle(pipeHandle);
- }
- else
- {
- Console.WriteLine("Failed to create named pipe. Error code: " + Marshal.GetLastWin32Error());
- }
- Console.WriteLine("Press Enter to exit...");
- Console.ReadLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement