C# 如何修复“连接尝试失败,因为连接方在一段时间后没有正确响应......”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1187783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:21:20  来源:igfitidea点击:

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

c#socketstcpnat

提问by Martin Vseticka

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.

我正在用 C# 制作游戏,我想显示对手的进度(动作等)。所以我通过 TCP 协议将游戏中的事件发送给对手。

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():

我已经在 localhost 上尝试过我的应用程序并且它可以工作,但是当我尝试使用我的外部地址以通过 Internet 进行通信时,我在类 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)

连接尝试失败,因为连接方在一段时间后没有正确响应,或者由于连接的主机未能响应(我的外部IP地址):(端口)而建立的连接失败

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.

我认为问题是我落后于 NAT。但是我已经为 IP 10.0.0.1 上的端口 49731 设置了端口转发,并且没有任何改变。

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

我的第二个猜测是 Windows 防火墙,但即使我停止了防火墙,我的应用程序也没有开始工作。

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!

有没有办法检查什么是错误的?非常感谢帮助!

采纳答案by Martin Vseticka

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.

我发现了问题所在。我在 10.0.0.1 上收听并尝试访问我的外部 IP(我的程序的第二个实例),这在只有一个 Internet 连接的计算机上是不可能的。

回答by Xin

I also faced the same problem in AWS VPN.

我在 AWS VPN 中也遇到了同样的问题。

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

我将proxy.company.com(外部IP)更改为10.0.0.5。

And it works now.

它现在有效。