连接尝试失败,因为连接方之后没有正确响应

时间:2014-12-01 16:29:59

标签: c# networking tcp socketexception

我这里有问题。每次我启动我的测试程序时,我似乎都会得到一个SocketException。 Localhost og IP:127.0.0.1没问题,我测试时防火墙关闭了。当我在我的Akademy和家里时,错误就出现了。

PS。它是用Visual Studio 2013 Ultimate编写的C#控制台应用程序。

====来源代码====

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MasserAfTesting {
    class Program {
        static void Main(string[] args) {
            int port = 2520;
            string ip = "91.236.210.60";

            new Thread(new Manager(port).Run).Start();
            Thread.Sleep(200);
            new Thread(new Client(ip, port).Run).Start();
        }
    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MasserAfTesting {
    class Manager {
        private int port;


        public Manager(int port) {
            this.port = port;
        }

        public void Run() {
            TcpListener listener = new TcpListener(port);
            listener.Start();
            while (true) {
                new Thread(new Worker(listener.AcceptTcpClient()).Run).Start();
            }
        }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MasserAfTesting {
    class Worker {
        private TcpClient client;

        public Worker(TcpClient client) {
            this.client = client;
        }

        public void Run() {
            NetworkStream stream = client.GetStream();
            Console.WriteLine("Worker Online...");
        }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace MasserAfTesting {
    class Client {

        TcpClient client;

        public Client(string ip, int port) {
            this.client = new TcpClient(ip, port);
        }

        public void Run() {
            NetworkStream stream = client.GetStream();
            Console.WriteLine("Client online...");
        }
    }
}

2 个答案:

答案 0 :(得分:-1)

发现TcpListener需要端口和IP才能正常运行。

答案 1 :(得分:-2)

未处理的异常:System.Net.Sockets.SocketException:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应188.114.140.7:2520    在System.Net.Sockets.TcpClient..ctor(String hostname,Int32 port)    在MasserAfTesting.Client..ctor(String ip,Int32 port)中的c:\ Users \ Jacob \ Documents \ Visual Studio 2013 \ Projects \ SWA \ MasserAfTesting \ MasserAfTesting \ Client.cs:第14行    在MasserAfTesting.Program.Main(String [] args)c:\ Users \ Jacob \ Documents \ Visual Studio 2013 \ Projects \ SWA \ MasserAfTesting \ MasserAfTesting \ Program.cs:第16行

IP中的差异原因是因为此测试是在家中进行的,但源代码是来自学校的IP。