Hello everyone,
I’m currently trying to implement a threaded IPC service with named pipes in PipeTransmissionMode.Message. When reading received messages from the server stream, the thread gets stuck in an infinite loop because IsMessageComplete never evaluates to true.
The problem occurs in Unity 5.6.1f1 as well as 2007.1, but not in a .NET 4.5.2 console application using the identical code.
Having spent a whole day on trying to figure this out I’d very much appreciate if someone could point me in the right direction. I’m not sure if I’m doing something wrong or this is a bug in Unity.
Here is a minimal working example:
using UnityEngine;
using System.IO.Pipes;
using System.Threading;
using System.Text;
using System.IO;
public class MinimalPipeExample : MonoBehaviour {
public string pipe = "MinimalPipeExamplePipe";
void Start() {
new Thread(runServer).Start();
Thread.Sleep(1000); // wait until the server is running
using (NamedPipeClientStream cs = new NamedPipeClientStream(".", pipe, PipeDirection.Out)) {
cs.Connect();
byte[] message = Encoding.UTF8.GetBytes("Hello World");
cs.Write(message, 0, message.Length);
cs.Flush();
Debug.Log("C Message sent");
}
}
void runServer() {
using (NamedPipeServerStream ss = new NamedPipeServerStream(pipe, PipeDirection.In, 1, PipeTransmissionMode.Message)) {
ss.WaitForConnection();
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[32];
do {
int bytesReceived = ss.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, bytesReceived);
Debug.Log("S Some bytes read; message complete: " + ss.IsMessageComplete);
// infinite loop here because IsMessageComplete is never true
} while (!ss.IsMessageComplete);
Debug.Log("S Message received: " + Encoding.UTF8.GetString(ms.ToArray()));
}
}
}