- Home /
ReadLine from Named Pipe freezes Unity
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?
Can you try this?
IEnumerator Listen()
{
string message = string.Empty;
while (sr.Peek >= 0)
{
message += sr.ReadLine();
yield return null;
}
yield break;
}
Hmm... $$anonymous$$aybe. Try not to use Coroutine at start or awake? While true too.
Try replace
StartCoroutine(Listen());
To this
Invoke("Listen",1f);
And this
public string message = "";
void Listen()
{
message = sr.ReadToEnd();;
}
Still freezes.
I think I'll try to make a separate thread for the interprocess communication because I will be able to make ReadLine read until the line escaping sequence without freezing the main thread.
However, I'm still waiting for any ideas that might help me.
Answer by adam_2015 · May 04, 2016 at 03:07 PM
I have finally made it work. As I said yesterday I tried to make it with a separate thread and it that solved the problem.
The following works as intended - the thread waits for event which is triggered (set) by changing messageTo variable which gets sent to another process. Then the thread keeps on reading until the message is not empty - thus we got some response from another process. And that repeats for until run (which is the condition of the main loop of the second thread) is set to false.
Here's my code:
using UnityEngine;
using System.IO.Pipes;
using System.IO;
using System.Threading;
using System.ComponentModel;
public class WEB_HANDLER : MonoBehaviour
{
private string pipeName
{
get
{
return "PIPE";
}
}
private NamedPipeClientStream stream;
private StreamWriter sw;
private StreamReader sr;
/// <summary>
/// Thread for inter process communication
/// </summary>
private Thread interProc;
/// <summary>
/// When set tells thread to continue its work.
/// </summary>
private AutoResetEvent msgEvent;
/// <summary>
/// Must-have for get{} in messageTo
/// </summary>
private string tmpMessageTo;
/// <summary>
/// Message that will be sent to another process. Sets msgEvent automatically.
/// </summary>
private string messageTo
{
get
{
return tmpMessageTo; //Required so it doesn't cause infinite loop.
}
set
{
tmpMessageTo = value;
msgEvent.Set(); //Setting event will cause second thread to continue its work.
}
}
private string messageFrom;
/// <summary>
/// Should 2nd thread be still running?
/// </summary>
private volatile bool run = true;
void Start()
{
msgEvent = new AutoResetEvent(false); //False means that it will not trigger the event when it's created.
}
void Update()
{
//Sending messages to the pipe
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("[IPC] Changing message to server");
messageTo = "message";
Debug.Log("[IPC] Success");
}
//Starting the thread
if (Input.GetKeyDown(KeyCode.LeftControl))
{
if (interProc != null && interProc.IsAlive)
{
Debug.Log("[IPC] Thread is already running");
return;
}
Debug.Log("[LOCAL INFO] Starting new thread");
interProc = new Thread(Listen);
interProc.Start();
}
//Stooping thread
if (Input.GetKeyDown(KeyCode.Escape))
{
Debug.Log("Stopping the thread");
run = false;
if (interProc != null)
{
if (interProc.ThreadState != ThreadState.Aborted)
interProc.Abort();
}
}
}
/* --- SECOND THREAD ---*/
/// <summary>
/// Initialises writers/readers and the pipe
/// </summary>
void Initialise()
{
//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...");
try
{
stream.Connect(120);
}
catch (Win32Exception)
{
Debug.LogError("[IPC] Server not running");
run = false;
return;
}
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;
}
void Listen()
{
Initialise();
while (run) //Main loop of the thread
{
messageFrom = "";
Debug.Log("[2T-IPC] Waiting for change of message event");
msgEvent.WaitOne(); //Waiting for event to be triggered (set)
Debug.Log("[2T-IPC] Sending test message");
sw.WriteLine(messageTo); //Writing command to the pipe
Debug.Log("[2T-IPC] Waiting for pipe drain");
stream.WaitForPipeDrain(); //Waiting for another process to read the command
messageFrom = sr.ReadLine(); //Reading
if (messageFrom.Length > 0)
{
Debug.Log(messageFrom);
}
}
Debug.Log("Finished");
}
/* --- UNITY'S THREAD --- */
//The following should stop the thread on Editor and Standalone quit and also when the game object is destroyed.
public void OnApplicationQuit()
{
run = false;
if (interProc != null)
{
if (interProc.ThreadState != ThreadState.Aborted)
interProc.Abort();
}
}
public void OnDestroy()
{
run = false;
if (interProc != null)
{
if (interProc.ThreadState != ThreadState.Aborted)
interProc.Abort();
}
}
}
So here's a little how-to-use of my code: 1. Attach the script to any game object 2. You have to have pipe server configured 3. Run the pipe server 4. Run the game 5. Press left control to run second thread 6. Press space to send the message
Your answer
Follow this Question
Related Questions
Using Pipes/Streams Freezes Unity 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Renderer on object disabled after level reload 1 Answer
What could be freezing unity? 2 Answers