2011-09-22 125 views
1

我在win7和xp中都遇到了.NET 4套接字(TcpClient)的一個簡單問題。.NET 4新的TCP客戶端無法連接:因目標機器主動拒絕而無法建立連接

我得到的錯誤:

無連接可以作出,因爲目標機器積極地拒絕它

這似乎並非是一個防火牆的問題,因爲客戶端和服務器程序上的同一臺計算機,並且我沒有啓用任何本地防火牆。

我寫的服務器和客戶機(它們在端口80講(我也嘗試過其他的端口,如31000)閒來無事在端口80上運行我的機器上

的客戶端代碼。:

public void makeConnection() 
    { 
     string server = ClientStatus.myself.ServerName; 
     port = 80; 
     ClientStatus.myself.BytesSent = 0.ToString(); 
     client = new TcpClient(server, port); 
     ClientStatus.myself.Connected = "connected"; 
     stream = client.GetStream(); 
     bytes = new Byte[1024]; 
    } 

,我confired服務器和端口是什麼我期待。在新的TcpClient(服務器,端口)時發生錯誤,且錯誤發生之前它旋轉約4秒鐘。我也使用嘗試IP地址(127.0.0.1)而不是「myhostname.domain.com」作爲服務器(創建客戶端套接字的替代方法),並且它也失敗。

下面是我寫的服務器代碼:

命名空間SocketListener { 類的DataListener { 公共靜態的DataListener自己; TcpListener server = null; 字節[]字節; Int32端口; IPAddress localAddr; MainWindow w;

public DataListener(MainWindow caller) 
    { 
     DataListener.myself = this; 
     w = caller; 
     Status.myself.Connected = "starting"; 
     port = 80; 
     localAddr = IPAddress.Parse("127.0.0.1"); 
     server = new TcpListener(localAddr, port); 
     bytes = new Byte[1024]; 
     server.Start(); 
    } 

    public void acceptLoop() 
    { 
     TcpClient client; 
     while (true) 
     { 
      // Perform a blocking call to accept requests. 
      Status.myself.Connected = "waiting"; 
      if (server.Pending()) 
      { 
       client = server.AcceptTcpClient(); 
       Status.myself.Connected = "true"; 
       Status.myself.BytesReceived = 0.ToString(); 
       NetworkStream stream = client.GetStream(); 
       dataLoop(stream); 
       client.Close(); 
      } 
      else 
      { 
       Thread.Sleep(100); 
       return; 
      } 
      // Shutdown and end connection 
      Status.myself.Connected = "false"; 
     } 
    } 

    public void dataLoop(NetworkStream stream) 
    { 
     int count = 0; 
     int i; 
     Status.myself.ByteRate = "0.0"; 
     Stopwatch watch = new Stopwatch(); 
     watch.Start(); 
     while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) 
     { 
      count += i; 
      Status.myself.BytesReceived = count.ToString(); 
     } 
     watch.Stop(); 
     double rate = count/(watch.ElapsedMilliseconds/1000); 
     rate = rate/(1024 * 1024); 
     Status.myself.ByteRate = rate.ToString(); 
    } 

    public void shutdown() 
    { 
     server.Stop(); 
    } 

} 

}

+0

檢查這個[問題] [1] [1]:HTTP://計算器。 com/questions/2972​​600/no-connection-could-be-made-because-the-target-machine-active-refused-it –

+0

再試一次並使用'IPAddr ess.Any'和客戶端的'IpAddress.Loopback'。 – jgauffin

回答

相關問題