2014-12-01 50 views
0

我在這裏有一個問題。每次啓動我的測試程序時,我都會看到SocketException。 Localhost或IP:127.0.0.1沒有問題,測試時防火牆關閉。當我在我的學習和在家時,這個錯誤就會出現。連接嘗試失敗,因爲連接方沒有正確迴應後

PS。這是一個用Visual Studio 2013 Ultimate編寫的C#控制檯應用程序。

====源代碼====

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 

namespace MasserAfTesting { 
    class Program { 
     static void Main(string[] args) { 
      int port = 2520; 
      string ip = "91.236.210.60"; 

      new Thread(new Manager(port).Run).Start(); 
      Thread.Sleep(200); 
      new Thread(new Client(ip, port).Run).Start(); 
     } 
    } 
} 



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

namespace MasserAfTesting { 
    class Manager { 
     private int port; 


     public Manager(int port) { 
      this.port = port; 
     } 

     public void Run() { 
      TcpListener listener = new TcpListener(port); 
      listener.Start(); 
      while (true) { 
       new Thread(new Worker(listener.AcceptTcpClient()).Run).Start(); 
      } 
     } 

    } 
} 



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

namespace MasserAfTesting { 
    class Worker { 
     private TcpClient client; 

     public Worker(TcpClient client) { 
      this.client = client; 
     } 

     public void Run() { 
      NetworkStream stream = client.GetStream(); 
      Console.WriteLine("Worker Online..."); 
     } 

    } 
} 



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

namespace MasserAfTesting { 
    class Client { 

     TcpClient client; 

     public Client(string ip, int port) { 
      this.client = new TcpClient(ip, port); 
     } 

     public void Run() { 
      NetworkStream stream = client.GetStream(); 
      Console.WriteLine("Client online..."); 
     } 
    } 
} 
+1

套接字異常的細節是什麼?任何內部異常?詳情?請發佈。 – BenjaminPaul 2014-12-01 16:35:47

+1

你忘了問一個問題。當你按下「提問問題」按鈕時,你應該問一個問題。 – 2014-12-02 18:16:54

+0

夥計,再次閱讀文本。這個問題被嵌入到文本中。 「我得到一個socketexception」,基本上尖叫着「爲什麼!?!」 – JacksonBolter 2014-12-02 22:00:18

回答

-1

發現TcpListener需要端口和IP才能正常工作。

-2

未處理的異常:System.Net.Sockets.SocketException:A連接嘗試失敗,因爲連接的方沒有正確一段時間後做出反應,或建立的連接失敗,因爲連接的主機未能響應188.114.140.7:2520 at System.Net.Sockets.TcpClient..ctor(String hostname,Int32 port) at MasserAfTesting.Client..ctor(String ip,Int32 port)在c:\ Users \ Jacob \ Documents \ Visual Studio 2013 \ Projects \ SWA \ MasserAfTesting \ MasserAfTesting \ Client.cs中:第14行 位於MasserAfTesting.Program.Main(String [] args) \ Jacob \ Documents \ Visual Studio 2013 \ Projects \ SWA \ MasserAfTesting \ MasserAfTesting \ Program.cs:第16行

在IP中的差異的原因是因爲此測試是從家裏完成,但源代碼是與IP從學校。

相關問題