2013-09-30 51 views
0

我有應用程序主機WCF服務。 我打開通過BackgroundWorker雖然IP地址正確,但WCF中指定的IP地址錯誤的TCP錯誤

private bool isConnected; 
private BackgroundWorker asyncWorker = new BackgroundWorker(); 

    InitializeComponent();   
    asyncWorker.WorkerReportsProgress = true; 
    asyncWorker.WorkerSupportsCancellation = true; 
    asyncWorker.ProgressChanged += new ProgressChangedEventHandler 
        (bwAsync_ProgressChanged); 
    asyncWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler 
        (bwAsync_RunWorkerCompleted); 
    asyncWorker.DoWork += new DoWorkEventHandler(bwAsync_DoWork); 
    btnConnect.BackColor = Color.ForestGreen; 

這是我的連接按鈕單擊事件的連接:

private void btnConnect_Click(object sender, EventArgs e) 
    {    
     btnConnect.Enabled = false; 
     Interface.interfaceNumber = interfaceNumber; 
     asyncWorker.RunWorkerAsync(); 
    } 

而且DoWork的:

private void bwAsync_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker bwAsync = sender as BackgroundWorker; 
    try 
    { 
     if (!isConnected) 
     { 
      // Returns a list of ipaddress configuration 
      IPHostEntry ips = Dns.GetHostEntry(Dns.GetHostName()); 

      // Get machine ipaddress 
      IPAddress _ipAddress = IPAddress.Parse(tbServerIp.Text); 

      // Create the url that is needed to specify where the service should be started 
      urlService = "net.tcp://" + _ipAddress.ToString() + ":8000/MyService"; 

      // Instruct the ServiceHost that the type that is used is a ServiceLibrary.service1 
      //host = new ServiceHost(typeof(ServiceLibrary.service1)); 
      ServiceLibrary.service1 serviceInstance = new ServiceLibrary.service1(); 
      serviceInstance.CapturingEvent += yourServiceInstance_StartCapturingEvent; 
      serviceInstance.OnProcessExitedEvent += serviceInstance_OnProcessExitedEvent; 
      host = new ServiceHost(serviceInstance); 
      host.Opening += new EventHandler(host_Opening); 
      host.Opened += new EventHandler(host_Opened); 
      host.Closing += new EventHandler(host_Closing); 
      host.Closed += new EventHandler(host_Closed); 

      // The binding is where we can choose what transport layer we want to use. HTTP, TCP ect. 
      NetTcpBinding tcpBinding = new NetTcpBinding(); 
      tcpBinding.TransactionFlow = false; 
      tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign; 
      tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; 
      tcpBinding.Security.Mode = SecurityMode.None; // <- Very crucial 

      // Add a endpoint 
      host.AddServiceEndpoint(typeof(ServiceLibrary.IService1), tcpBinding, urlService); 

      // A channel to describe the service. Used with the proxy scvutil.exe tool 
      ServiceMetadataBehavior metadataBehavior; 
      metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>(); 
      if (metadataBehavior == null) 
      { 
       // Create the proxy object that is generated via the svcutil.exe tool 
       metadataBehavior = new ServiceMetadataBehavior(); 
       metadataBehavior.HttpGetUrl = new Uri("http://" + _ipAddress.ToString() + ":8001/MyService"); 
       metadataBehavior.HttpGetEnabled = true; 
       metadataBehavior.ToString(); 
       host.Description.Behaviors.Add(metadataBehavior); 
       urlMeta = metadataBehavior.HttpGetUrl.ToString(); 
      } 

      host.Open(); 
      isConnected = true; 
     } 
     else 
     { 
      if (asyncWorker.IsBusy) 
      { 
       //bnAsync.Enabled = false; 
       this.Invoke((MethodInvoker)delegate { lblStatus.Text = "Cancelling..."; }); 

       // Notify the worker thread that a cancel has been requested. 
       // The cancel will not actually happen until the thread in the 
       // DoWork checks the bwAsync.CancellationPending flag, for this 
       // reason we set the label to "Cancelling...", because we haven't 
       // actually cancelled yet. 
       asyncWorker.CancelAsync(); 
      } 

      host.Close(); 
      isConnected = false; 
     } 
    } 
    catch (Exception ex) 
    { 
     isConnected = false; 
     MessageBox.Show(ex.Message); 
     return; 
    } 
} 

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
{ 
    // Lock\Release buttons 
} 

我的應用程序成功地連接和所有工作正常,但在案件我指定錯誤的IP地址我得到TCP錯誤requested Ip Address is not valid這是好的,但萬一我修復這個錯誤的IP地址到公司矩形IP地址我仍然得到相同的錯誤,除非我的應用程序重新啓動。 也許我的線程仍在運行,這就是爲什麼我無法連接?

回答

2

首先不使用IP地址,除非你只是在做localhost開發,它總是一個好主意,使用DNS名稱或主機文件名條目。其次,我假設你的host變量是一個類成員變量(你上面沒有包含的代碼)。打開主機後,它的綁定將在服務器內存中保持活動狀態,直到您重新啓動標準慣例的應用程序。

該代碼的另一個問題是在bwAsync_DoWorkelse塊中,在單擊表單按鈕後關閉主機,但您沒有用更新後的表單數據重新綁定/重新打開主機。考慮做下面的事來解決這個問題。

  1. 將執行實際主機綁定的代碼移出bwAsync_DoWork到自己的方法中。
  2. bwAsync_DoWork的末尾調用此方法以確保打開新綁定。

代碼:

private void bwAsync_DoWork(object sender, DoWorkEventArgs e) 
{ 
    BackgroundWorker bwAsync = sender as BackgroundWorker; 
    if (asyncWorker.IsBusy) 
    { 
     this.Invoke((MethodInvoker)delegate { lblStatus.Text = "Cancelling..."; }); 

     asyncWorker.CancelAsync(); 
    } 
    else 
    { 
     if(isConnected) 
     { 
      host.Close(); 
      isConnected = false; 
     } 
     BindHost();   
    } 
} 


private void BindHost() 
{ 
    ... 
    isConnected = true; 
} 
+0

你能告訴我請了如何使用DNS名稱或主機文件名條目? – user2813889

+0

BTW我插入錯誤的IP地址後仍然收到相同的錯誤,並重新插入正確的一個 – user2813889