Skip to content

Instantly share code, notes, and snippets.

@JonathonReinhart
Last active May 23, 2023 23:44
Show Gist options
  • Save JonathonReinhart/bbfa618f9ad19e2ca48d5fd10914b069 to your computer and use it in GitHub Desktop.
Save JonathonReinhart/bbfa618f9ad19e2ca48d5fd10914b069 to your computer and use it in GitHub Desktop.
Named Pipes between C# and Python
import time
import struct
f = open(r'\\.\pipe\NPtest', 'r+b', 0)
i = 1
while True:
s = 'Message[{0}]'.format(i).encode('ascii')
i += 1
f.write(struct.pack('I', len(s)) + s) # Write str length and str
f.seek(0) # EDIT: This is also necessary
print('Wrote:', s)
n = struct.unpack('I', f.read(4))[0] # Read str length
s = f.read(n).decode('ascii') # Read str
f.seek(0) # Important!!!
print('Read:', s)
time.sleep(2)
void run_server()
{
// Open the named pipe.
var server = new NamedPipeServerStream("NPtest");
Console.WriteLine("Waiting for connection...");
server.WaitForConnection();
Console.WriteLine("Connected.");
var br = new BinaryReader(server);
var bw = new BinaryWriter(server);
while (true) {
try {
var len = (int) br.ReadUInt32(); // Read string length
var str = new string(br.ReadChars(len)); // Read string
Console.WriteLine("Read: \"{0}\"", str);
str = new string(str.Reverse().ToArray()); // Just for fun
var buf = Encoding.ASCII.GetBytes(str); // Get ASCII byte array
bw.Write((uint) buf.Length); // Write string length
bw.Write(buf); // Write string
Console.WriteLine("Wrote: \"{0}\"", str);
}
catch (EndOfStreamException) {
break; // When client disconnects
}
}
Console.WriteLine("Client disconnected.");
server.Close();
server.Dispose();
}
@dchc123
Copy link

dchc123 commented Mar 24, 2021

Almost 9 years old but still fantastic! Very nearly works straight away. The only major change I remember making is line 11 of the .py file.

f.write(struct.pack('I', len(s)) + s)   # Write str length and str

Python produces error when concatenating string and byte types. Should be changed to:

f.write(struct.pack('I', len(s)) + str.encode(s))  # Write str length and str

@JonathonReinhart
Copy link
Author

Hi @dchc123. I edited your comment to add code formatting, making it much easier to read.

My original gist was written for Python 2. I updated it for Python 3 (but didn't test it since I rarely use Windows now):

  • Use print() function syntax
  • Call .encode('ascii') on message to be sent and .decode('ascii') on the received message
    • I prefer an explicit encoding rather than the default encoding which is used by your suggestion of (str.encode(s)). The default encoding is often UTF-8. Since the C# side used ASCII, it should be the same on both sides.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment