Send a message from one program to another in Unity

I have two different executables running on the same Windows machine. Both are built in Unity. I want to send a message from one to another without using a network .

How do you send a message from an exe program to another exe program in Unity?

Is this possible with help integrated Mono/.net functionalityor something else?

+4
source share
2 answers

You can use Named Pipes, which uses shared memory to communicate with another application on the same machine .

→ ... , 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();

StreamString MS Doc:

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;
    }
}
+7

, . , , .

+1

Source: https://habr.com/ru/post/1017374/


All Articles