我有两个不同的可执行文件在同一台运行Windows OS的计算机上运行。它们都是在Unity中构建的。我想将消息从一个发送到其他而不使用网络。
如何从exe程序向Unity中的另一个exe程序发送消息?
这可能与integrated Mono/.net functionality
或其他内容有关吗?
答案 0 :(得分:9)
您可以使用命名管道,它使用共享内存与相同计算机上的其他应用程序进行通信。
转到文件 - > 构建设置... 选择 PC,Mac& Linux Standalone 然后单击播放器设置... 。现在,将 Api兼容级别更改为 .NET 2.0 。
关闭并重新打开Visual Studio。现在,您可以导入using System.IO.Pipes;
并能够使用NamedPipeServerStream
和NamedPipeClientStream
。
下面是一个非常简化的服务器和客户端。您必须在Thread
中执行此操作,并且还应处理异常。
如果您不想使用Thread
,还有异步参数(PipeOptions.Asynchronous
)使其成为非阻塞运算符。它从那里变得复杂,你必须在MS doc上寻找一些例子。
简单服务器:
//Create Server Instance
NamedPipeServerStream server = new NamedPipeServerStream("MyCOMApp", PipeDirection.InOut, 1);
//Wait for a client to connect
server.WaitForConnection();
//Created stream for reading and writing
StreamString serverStream = new StreamString(server);
//Send Message to Client
serverStream.WriteString("Hello From Server");
//Read from Client
string dataFromClient = serverStream.ReadString();
UnityEngine.Debug.Log("Received from Client: " + dataFromClient);
//Close Connection
server.Close();
简单客户:
//Create Client Instance
NamedPipeClientStream client = new NamedPipeClientStream(".", "MyCOMApp",
PipeDirection.InOut, PipeOptions.None,
TokenImpersonationLevel.Impersonation);
//Connect to server
client.Connect();
//Created stream for reading and writing
StreamString clientStream = new StreamString(client);
//Read from Server
string dataFromServer = clientStream.ReadString();
UnityEngine.Debug.Log("Received from Server: " + dataFromServer);
//Send Message to Server
clientStream.WriteString("Bye from client");
//Close client
client.Close();
来自MS Doc的StreamString
课程:
public class StreamString
{
private Stream ioStream;
private UnicodeEncoding streamEncoding;
public StreamString(Stream ioStream)
{
this.ioStream = ioStream;
streamEncoding = new UnicodeEncoding();
}
public string ReadString()
{
int len = 0;
len = ioStream.ReadByte() * 256;
len += ioStream.ReadByte();
byte[] inBuffer = new byte[len];
ioStream.Read(inBuffer, 0, len);
return streamEncoding.GetString(inBuffer);
}
public int WriteString(string outString)
{
byte[] outBuffer = streamEncoding.GetBytes(outString);
int len = outBuffer.Length;
if (len > UInt16.MaxValue)
{
len = (int)UInt16.MaxValue;
}
ioStream.WriteByte((byte)(len / 256));
ioStream.WriteByte((byte)(len & 255));
ioStream.Write(outBuffer, 0, len);
ioStream.Flush();
return outBuffer.Length + 2;
}
}
答案 1 :(得分:1)
你可以有一个他们都写和读的文件。 您可以在其中加上时间戳,以显示上次写入消息的时间