首页 > 解决方案 > 无法连接到本地主机。是客户端问题还是本地主机问题?

问题描述

我正在尝试创建一个线程,以使侦听器在 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"

标签: c#socketsvisual-studio-2013tcpclienttcplistener

解决方案



推荐阅读