Martin Tomko
Martin Tomko

Reputation: 155

SocketPolicy exception int TCP Connection between unity and C# server

I am working on simple multiplayer game where i am working on my own coded server (in C#).

On the server there is TCPListener:

 public void StartClientHandler()
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine("ClientHandler started");
        Console.ForegroundColor = ConsoleColor.White;
        TcpListener server = null;
        try
        {
            Int32 port = 4200;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            server = new TcpListener(localAddr, port);
            server.Start();


            while (true)
            {
                TcpClient client = server.AcceptTcpClient();
                lobby.addToOnline(new Client(client,lobby));
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
        }

    }

and the unity client has TCPClient:

static public bool InitializeConnection()
{
    try
    {
        client.Connect(ip, port);
        if (client.Connected)
        {
            stream = client.GetStream();
            Thread listener = new Thread(new ThreadStart(Listener));
            listener.Start();
        }
        else Debug.Log("not connected:(");

        return client.Connected;
    }
    catch (Exception e)
    {
        Debug.Log(e.StackTrace);
        return false;
    }


}

Locally (using "localhost" address) everything works perfect! But when i am trying to test it with friend over internet or local ip it trows this exception:

at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy) [0x00000] in :0 at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in :0 at System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint remote_end_point) [0x00000] in :0 at System.Net.Sockets.TcpClient.Connect (System.Net.IPAddress[] ipAddresses, Int32 port) [0x00000] in :0 UnityEngine.Debug:Log(Object)

Where can be problem? I read something about it and the problem should appear only in unity web player right? But i am building it for windows (EXE file) but i tried also build it into WEB GL player (There was problem because of thread)

PS. I forwarded port 4200 in my router to my server (for over internet connection)

Thanks for any help

Upvotes: 0

Views: 729

Answers (1)

Martin Tomko
Martin Tomko

Reputation: 155

Ok problem wasn't in policy. Even i forwarded port my server wasn't listening on that opened port.

I am not sure what exactly was the problem but form server code i changed ip form 127.0.0.1 to 0.0.0.0 and Type of port form Int32 to classic int.

And that fixed my problem.

If someone would be able to explain i would be glad :)

Upvotes: 1

Related Questions