Hi everyone.
I've got a problem which is that ReadLine method (StreamReader) freezes Unity when trying to read from a named pipe and that happens just after I start the game or to be more precise when I start to read.
I need to receive as well as send messages using the pipe to another process and ideally I would like to be able to listen to the pipe constantly and send a message at any time.
Here's my code:
using UnityEngine;
using System.Collections;
using System.IO.Pipes;
using System.IO;
public class WEB_HANDLER : MonoBehaviour
{
private string pipeName
{
get
{
return "PIPE";
}
}
private NamedPipeClientStream stream;
private StreamWriter sw;
private StreamReader sr;
void Start()
{
//Starting the pipe
Debug.LogFormat("[IPC] Creating new ClientStream. Pipe name: {0}", pipeName);
stream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut);
//Connecting to the pipe
Debug.Log("[IPC] Connecting...");
stream.Connect(120);
Debug.Log("[IPC] Connected");
//Initialising Readers/Writers
Debug.Log("[IPC] Starting StreamReader");
sr = new StreamReader(stream);
Debug.Log("[IPC] Starting StreamWriter");
sw = new StreamWriter(stream);
//AutoFlush
Debug.Log("[IPC] AutoFlush = true");
sw.AutoFlush = true;
Debug.Log("[IPC] Starting listening coroutine");
StartCoroutine(Listen());
}
void Update()
{
//Sending messages to the pipe
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("[IPC] Sending message to server");
sw.WriteLine("Test message");
Debug.Log("[IPC] Success");
}
}
IEnumerator Listen()
{
while (true)
{
string message = sr.ReadLine();
if (message.Length > 0) //If message is not empty then print it
{
Debug.Log(message);
}
yield return new WaitForEndOfFrame();
}
}
My guess is that I'm reading an empty string and there is no escape sequence in it so it keeps on reading nothing. If I'm right, how can I solve the problem?
↧