无法建立连接,因为目标计算机主动拒绝它 - 使用Socket或TcpClient

jp2*_*ode 3 c# tcpclient visual-studio-2008 winforms

很多人都有同样的问题,但每个人的实现都不同.

我需要帮助实现它.

void sendUsingTcp() 
{
    try 
    {
        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(172.16.8.200), 8000);
        sock.Connect(endPoint);
        // code past this never hits because the line above fails
    } 
    catch (SocketException err) 
    {
        MessageBox.Show(err.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过直接使用相同错误结果的TCP客户端:

void sendUsingTcp() 
{
    try 
    {
        using (TcpClient client = new TcpClient()) 
        {
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(172.16.8.200), 8000);
            client.Connect(endPoint);
            // code past this never hits because the line above fails
        }
    } 
    catch (SocketException err) 
    {
        MessageBox.Show(err.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的电脑的IP地址是172.16.11.144.

Raf*_*off 5

事实证明,我的服务器正在侦听来自同一IP的传入连接.我不得不改变它的代码来监听任何IP.

之前和错误:

IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(172.16.8.200), 8000);
Run Code Online (Sandbox Code Playgroud)

有问题的修正:

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8000);
Run Code Online (Sandbox Code Playgroud)