How to fix “a connection attempt failed because the connected party did not properly respond after a period of time …” error?

不问归期 提交于 2020-01-11 04:54:05

问题


I'm making a game in C# and I want to display the progress (movements and so on) of opponent. So I send events in game via TCP protocol to opponent.

I've already tried my application on localhost and it works but when I try to use my external address in order to communicate over the internet I get the error below in class TcpInformer.Connect():

a connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond (my external IP address):(port)

I thought the problem was that I was behind NAT. But I've already set up portforwarding for port 49731 on IP 10.0.0.1 and nothing changed.

My second guess was Windows firewall but even when I stopped the firewall my app didn't start working.

My code for connecting of the two PCs is:



        TcpInformer peer;
        TcpHost server;

        public void PrepareConnection() // for server (host)
        {
            playerType = PlayerType.One;
            server = new TcpHost(form, this);
            server.Start("10.0.0.1", 49731);
        }

        public void PrepareConnection2() // for client
        {
            playerType = PlayerType.Two;
            peer = new TcpInformer(form, this);
            peer.Connect("MY EXTERNAL IP", 49731);
        }


// classes TcpHost and TcpInformer

    public interface ITcpCommunication
    {
        #region Operations (3) 

        void ReadData();

        void SendData(byte[] message);

        void SendData(byte[] message, int size);

        #endregion Operations 
    }

    public class TcpInformer : ITcpCommunication
    {
        #region Fields (9) 

        private NetworkStream con_ns;
        private TcpClient con_server;
        private bool connected;
        private Fmain form;
        private SecondPlayer player;
        private int port;
        private string server;
        private string stringData;

        #endregion Fields 

        #region Delegates and Events (1)

        // Events (1) 

        public event SimulationEventHandler ReadEvent;

        #endregion Delegates and Events 

        #region Constructors (1) 

        public TcpInformer(Fmain form, SecondPlayer player)
        {
            this.form = form;
            connected = false;
            this.player = player;
        }

        #endregion Constructors 

        #region Methods (6) 

        // Public Methods (5) 

        /// 
        /// 
        /// 
        /// e.g., server = "127.0.0.1"
        /// e.g., port = 9050
        public void Connect(string server, int port) 
        {
            this.port = port;
            this.server = server;
            connected = true;

            try
            {
                con_server = new TcpClient(this.server, this.port);
            }
            catch (SocketException ex)
            {
                connected = false;
                MessageBox.Show("Unable to connect to server" + ex.Message);
                return;
            }

            con_ns = con_server.GetStream();
        }

        public void Disconnect()
        {
            form.Debug("Disconnecting from server...", "Player2Net");
            con_ns.Close();
            con_server.Close();
        }

        public void ReadData()
        {
            if (con_ns != null)
            {
                if (con_ns.DataAvailable)
                {
                    byte[] data = new byte[1200];
                    int received = con_ns.Read(data, 0, data.Length);

                    player.ProcessReceivedData(data, received);
                }
            }
            else
            {
                form.Debug("Warning: con_ns is not inicialized.","player2");
            }
        }

        public void SendData(byte[] message)
        {
            con_ns.Write(message, 0, message.Length);
            con_ns.Flush();
        }

        public void SendData(byte[] message, int size)        
        {
            if (con_ns != null)
            {
                con_ns.Write(message, 0, size);
            }
        }
        // Private Methods (1) 

        private void Debug(string message)
        {
            form.Debug("Connected to: " + server + "port: " + port.ToString() + ": " + message, "Player2Net");
        }

        #endregion Methods 
    }

    public class TcpHost : ITcpCommunication
    {
        #region Fields (9) 

        private ASCIIEncoding enc;
        private Fmain form;
        private TcpListener listener;
        private SecondPlayer player;
        private int port;
        private Socket s;
        private string server;
        private bool state;

        #endregion Fields 

        #region Delegates and Events (1)

        // Events (1) 

        public event SimulationEventHandler ReadEvent;

        #endregion Delegates and Events 

        #region Constructors (1) 

        public TcpHost(Fmain form, SecondPlayer player)
        {
            this.player = player;
            this.form = form;
            state = false;
            enc = new ASCIIEncoding();
        }

        #endregion Constructors 

        #region Methods (5) 

        // Public Methods (5) 

        public void Close()
        {
            state = false;
            s.Close();
            listener.Stop();
        }

        public void ReadData()
        {
            if (state == true)
            {
                if (s.Available > 0) // if there's any data
                {
                    byte[] data = new byte[1200];
                    int received = s.Receive(data);
                    player.ProcessReceivedData(data, received);
                }
            }
        }

        public void SendData(byte[] message)
        {
            if (state == true)
            {
                s.Send(message);
            }
        }

        public void SendData(byte[] message, int size)
        {
            if (state == true)
            {
                s.Send(message, size, SocketFlags.None);
            }
        }

        public void Start(string p_ipAddress, int listenPort)
        {
            //IPAddress ipAddress = IPAddress.Loopback
            IPAddress ipAddress = IPAddress.Parse(p_ipAddress);

            IPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, listenPort); 

            //listener = new TcpListener(ipAddress, listenPort);
            listener = new TcpListener(ipLocalEndPoint);
            server = "[provider]";
            port = listenPort;
            listener.Start();
            form.Debug("Server is running", "Player1Net");
            form.Debug("Listening on port " + listenPort, "Player1Net");
            form.Debug("Waiting for connections...", "Player1Net");
            s = listener.AcceptSocket();
            form.Debug("Connection accepted from " + s.RemoteEndPoint, "Player1Net");
            state = true;
        }

        #endregion Methods 
    }


Is there a way how to check what is wrong? Help is much appreciated!


回答1:


I found out what was the problem. I was listening on 10.0.0.1 and trying to reach my external IP (second instance of my program) which is impossible on a computer with one connection to the internet.




回答2:


I also faced the same problem in AWS VPN.

I changed the proxy.company.com (external ip) to 10.0.0.5.

And it works now.



来源:https://stackoverflow.com/questions/1187783/how-to-fix-a-connection-attempt-failed-because-the-connected-party-did-not-prop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!