无法连接到本地主机。是客户端还是本地主机问题?

时间:2019-09-19 13:13:01

标签: c# sockets visual-studio-2013 tcpclient tcplistener

我正在尝试创建一个线程,该线程使侦听器保持活动状态为127.0.0.1。我正在使用以下代码创建侦听器:

        IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); //Localhost Ip Address
        TcpListener connectionListner = new TcpListener(ipAddress, 2003); 
        connectedSocket = connectionListner.AcceptSocket();
        connectionListner.Start();

我在客户端遇到问题。 当我尝试将客户端连接到上面创建的localhost(独立程序)时,出现错误

客户代码:

class Client
{        
    static void Main(string[] args)
    {
        Console.WriteLine("client has started." + Environment.NewLine);            
        connectToLocalHost();
    }

    static void connectToLocalHost()
    {
        string ipaddress = "127.0.0.1";
        int port = 2003;
        try
        { 
            TcpClient client = new TcpClient(ipaddress, port);
            NetworkStream stream = client.GetStream();
            Byte[] data = new Byte[256]; // Buffer to store the response bytes.

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            Console.WriteLine("Received: {0}", responseData);

            // Close everything.
            stream.Close();
            client.Close();
           }
        catch (SocketException SE)
        {
            Console.WriteLine("Socket Error..... " + SE.StackTrace);
        }
    }
}

错误:

  

Message =“无法建立连接,因为目标计算机   主动拒绝了127.0.0.1:2003“

1 个答案:

答案 0 :(得分:0)