1

I am trying to make an andorid app that commuicates with my server via Unity 5.4. The Devices need to be in the same network to do so.

For that i am using System.Net.Sockets and a TcpClient to connect to my server. Everything works well when i run it out of the Editor, or build it as a Windows standalone.The communication between a pc hosting the service and a diffrent pc running the standalone is possible and working as intended. As soon as i build it as an .apk and install it on my smartphone i will get a SocketException. Also my phone is stuck loading for quite some time

Is using a TcpClient, is that possible on android with unity3d ?

The Exception i get is:

System.Net.Sockets.SocketException: Connection timed out

I made sure that both devices are in the same network, e.g. the Ip for my Pc hosting the server is 192.168.178.24 and the ip for my smartphone is 192.168.178.113.

The ports required are open and the firewall lets data through.

I am runnig this code in Unity:

private TcpClient client;
private StreamWriter writer;

void Start()
{
    try
    {
        client = new TcpClient(AddressFamily.InterNetwork);
        IPAddress ipAddress = IPAddress.Parse(PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey));
        Debug.Log(ipAddress.ToString());
        client.Connect(ipAddress, 11000);
        writer = new StreamWriter(client.GetStream());
        Debug.Log("connected");
    }
    catch (ArgumentNullException ane)
    {
        Debug.Log(string.Format("ArgumentNullException : {0}", ane.ToString()));
    }
    catch (SocketException se)
    {
        Debug.Log(string.Format("SocketException : {0}", se.ToString()));
    }
    catch (Exception e)
    {
        Debug.Log(string.Format("Unexpected exception : {0}", e.ToString()));
    }
}

i double checked if the Ip adress recieved from the player prefs is correct, it is.

Has someone an idea what causes it to not even establish a connection ? I tried Wireshark on my pc, it didn't show any incoming packages, so my guess is the mistake is sometimes during establishing the connection.

Here is an image for my Log output from the smartphone: LogCat Output

Edit: Server Code

public class ServiceListener
{
    public TcpListener Listener;

    public void StartListening()
    {
        IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = Array.Find<IPAddress>(ipHostInfo.AddressList, ipMatch => ipMatch.AddressFamily == AddressFamily.InterNetwork);
        Listener = new TcpListener(ipAddress, 11000);
        Listener.Start();
    }

    public void StopListening()
    {
        Listener.Stop();
    }
}

static void Main()
    {
        ServiceListener currentListener = new ServiceListener();
        currentListener.StartListening();

        TcpClient currentClient = currentListener.Listener.AcceptTcpClient();
        StreamReader reader = new StreamReader(currentClient.GetStream());

        Console.WriteLine("Connected");

        while (true)
        {
            byte[] messageBytes = new byte[1024];


            if (!reader.EndOfStream)
            {

                string message = reader.ReadLine();
                string[] messageParts = message.Split('|');

                int xOffset = int.Parse(messageParts[0]);
                int yOffset = int.Parse(messageParts[1]);
                bool leftClick = bool.Parse(messageParts[2]);
                bool rightClick = bool.Parse(messageParts[3]);


                Console.WriteLine(string.Format("x:{0},y:{1},left:{2},right:{3}", xOffset, yOffset, leftClick, rightClick));
            }
            else
            {
                currentClient = currentListener.Listener.AcceptTcpClient();
                reader = new StreamReader(currentClient.GetStream());
            }
        }
    }
Kusakari13
  • 13
  • 1
  • 4
  • I just remembered this. Is this solved yet? – Programmer Aug 25 '16 at 23:20
  • It is wokring now, but i dont exactly know why. And i want to provide a solution for people having the same problem. I had some spare time when i was on the road so i tried it with my laptop, i copy and pasted my server code in a new project adn it worked. somehow my server just didnt accepted android, but using 100% the same code it worked after copy and pasting it in a new project – Kusakari13 Aug 27 '16 at 09:29
  • I tried it to and it worked out of the box. It was likely a firewall problem. You can implement it with another Thread or use asynchronous method. Happy coding! – Programmer Aug 27 '16 at 09:34
  • the weird thing is, i have 2 consoles with exact the same code i can move both to a pc i didnt use before, one works fine, the other one won't i have to look into it And thanks a lot, i appreciate the time and effort you'd put into it – Kusakari13 Aug 27 '16 at 11:15

1 Answers1

0

Is using a TcpClient, is that possible on android with unity3d ?

Yes, it is. It is very possible and should work.

Your problem is very likely to come from this line of code:

IPAddress ipAddress = IPAddress.Parse(PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey));

Since your hosting server IP is 192.168.178.24. Hardcode the value for testing purposes to see if PlayerPrefs.GetString(MenuManager.IpPlayerPrefKey) is returning an invalid IP Address.

Maybe something like:

IPAddress ipAddress = IPAddress.Parse("192.168.178.24");

Another thing to do in your server code is to put Application.runInBackground = true; in your Start() function. This will make sure that your server is running even when the Applciation is not on focus.

Finally, you are currently using synchronous server socket. When connecting, receiving data from the server, Unity will block/freeze until that operation completes. You should use asynchronous socket or run your server and client code in another Thread. This does not look like the current problem but you will run into it later on.

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • thanks for it ! i did tried a hardcoded ip before, it did work on standalone pc and editor but not on mobile. thats the thing that confuses me the most, that everything works for standalone pc and editor, but not mobile. my server is not running in unity, it is currently just a console application and it will be a windows service later on. thanks man, i will give asynchronous communication a try when i manage to get the current version running. – Kusakari13 Aug 19 '16 at 21:11
  • If you tried the hardcoded part and that didn't work, I suggest you try this in another network. Connect both devices to another router and test it. At the-same time, you should also post the server code in your question. – Programmer Aug 19 '16 at 21:16
  • i added the server code for the cosole application. also i tried it in 2 seperate networks – Kusakari13 Aug 19 '16 at 21:21
  • Ok. I will try to replicate that problem in few hours. Currently not on the computer to do that. Will let you know if I find anything. The problem now is just the connecting part? – Programmer Aug 19 '16 at 21:26
  • thanks for your time and efforet, i appreciate it. yes, the line that throws the exception is "client.Connect(ipAddress, 11000);" – Kusakari13 Aug 19 '16 at 21:33
  • Ok. I will be try it as soon as possible. – Programmer Aug 19 '16 at 21:37