We currently are developping an app that is sort of "add-on" app for our main app to extends its possibilities.
We asked ourselves if there's simple inter-app communication on same device (nothing found on the internet for this...). Our first thought was to create a server socket on our add-on app, and send data from main app to it.
Here's C# code for server :
public async Task Start()
{
Listener = new TcpListener(IPAddress.Parse(GetIP()), 7777);
var client = Listener.AcceptTcpClient();
while (true)
{
while (!client.GetStream().DataAvailable) ;
using (NetworkStream stream = client.GetStream())
{
byte[] data = new byte[client.Available];
stream.Read(data, 0, client.Available);
if (data.Length > 0)
{
String s = Encoding.UTF8.GetString(data);
if (!string.IsNullOrWhiteSpace(s))
OnMessageRecevied?.Invoke(s);
}
}
}
}
And for client :
public async Task SendMessage(string msg)
{
tClient = new TcpClient();
var buffer = Encoding.UTF8.GetBytes(msg);
while (!tClient.Connected)
{
tClient.Connect(IPAddress.Parse(Server.GetIP()), 7777);
Thread.Sleep(100);
}
await tClient.GetStream().WriteAsync(buffer, 0, buffer.Length);
tClient.Close();
}
It seems not working, cause we our main app takes focus, the add-on app seems like to stop listening.
Is this a generic way to communication between these two apps (always on same device) or will we have to develop separate solution ? if separate solutions, what's the best solution for iOS ? Android ? We used Xamarin for our add-on app, and we currently only target iOS and Android.
Note: because it's same device, we don't want to use distant webservice to communicate.