TCP通信具有随机延迟

TCP通信具有随机延迟,tcp,delay,Tcp,Delay,我制作了一个非常简单的客户端->服务器程序,它可以正常工作,但有时它会立即连接到服务器,但在其他情况下需要20秒以上,或者根本无法连接。即使在同一台PC上启动客户端和服务器,也会发生这种情况 客户: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; namespace TCPListen

我制作了一个非常简单的客户端->服务器程序,它可以正常工作,但有时它会立即连接到服务器,但在其他情况下需要20秒以上,或者根本无法连接。即使在同一台PC上启动客户端和服务器,也会发生这种情况

客户:

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

namespace TCPListener
{
class Program
{
    static void Main(string[] args)
    {

        TcpClient client = new TcpClient();
        client.Connect("95.102.185.157", 8001);
        Console.WriteLine("Connected");
        string message = Console.ReadLine();

        NetworkStream stream = client.GetStream();

        ASCIIEncoding ncoder = new ASCIIEncoding();
        Byte[] transfer = ncoder.GetBytes(message);
        stream.Write(transfer, 0, transfer.Length);



        client.Close();

        Console.ReadKey();
        }
    }
}
服务器:

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

namespace TCPServer
{
class Program
{
    static void Main(string[] args)
    {
        IPAddress ip = IPAddress.Parse("192.168.1.12");
        TcpListener listener = new TcpListener(ip, 8001);
        listener.Start();
        Console.WriteLine("Listening on " + ip.ToString());
        Socket s = listener.AcceptSocket();
        Console.WriteLine("Recieved socket" + s.RemoteEndPoint);

        Byte[] b = new Byte[100];
        s.Receive(b);
        foreach (Byte byt in b)
        {
            Console.Write(Convert.ToChar(byt));

        }

        ASCIIEncoding ncoder = new ASCIIEncoding();
        Byte[] message = ncoder.GetBytes("cud");
        s.Send(message);

        s.Close();
        listener.Stop();

        Console.ReadKey();
    }
}

}

我会确保您完全关闭了套接字和tcplistener。如果您使用
IPAddress构建服务器的tcplistener,会有什么区别吗?有没有任何
而不是特定的IP?我真的看不出区别,因为它在70%的情况下都无法连接。我认为它不能完全与IPAdress一起工作。有没有,本地主机也是如此