由于项目需求, 需要和另外一个程序之间通信。 在筛选了 进程间通信方案之后 选择 使用 命名管道的方法,操作简单容易实现:
测试过程中 发现 Unity3D在编辑状态下 会出现无响应状态, 发布之后没有这个问题 !
过几天我会写一个 unity3D 和 WindowsService 命名管道 进程通信的博客。 应为在WindowsService 中会有权限的问题
具体实现如下 Unity3d 端: 在这里 unity 充当 客户端 负责发送消息
这里需要注意下,设置Unity3D:
using UnityEngine;
using System;
using System.IO;
using System.IO.Pipes;
using System.Security.Principal;
public class ProcessCommunication : MonoBehaviour {
// Use this for initialization
public string content="";
public int count;
void OnGUI()
{
content = GUILayout.TextArea(content,GUILayout.Width(200));
if (GUILayout.Button("SendData"))
{
SendData( content+" "+(++count) );
}
}
private static void SendData(string str)
{
try
{
using (NamedPipeClientStream pipeClient =
new NamedPipeClientStream("localhost", "clouddeskpipeTest", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None))
{
pipeClient.Connect();
using (StreamWriter sw = new StreamWriter(pipeClient))
{
sw.WriteLine(str);
sw.Flush();
}
}
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
}
服务端我们测试用的是 ConsoleApplication 具体代码如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplicationWindowsService_Server
{
class Program
{
static void Main(string[] args)
{
WaitData();
}
private static void WaitData()
{
Console.WriteLine("pipeServer 初始化");
while (true)
{
try
{
NamedPipeServerStream pipeServer = new NamedPipeServerStream("clouddeskpipeTest", PipeDirection.InOut, 2);
pipeServer.WaitForConnection();
StreamReader sr = new StreamReader(pipeServer);
string con = sr.ReadLine();
Console.WriteLine("pipeServer 内容:" + con);
sr.Close();
Thread.Sleep(50);
Console.WriteLine("pipeServer 等待中:");
}
catch (Exception ex)
{
Console.WriteLine("pipeServer 异常:" + ex.Message);
}
}
}
}
}
测试过程中 发现 Unity3D在编辑状态下 会出现无响应状态, 发布之后没有这个问题 !
过几天我会写一个 unity3D 和 WindowsService 命名管道 进程通信的博客。 应为在WindowsService 中会有权限的问题