C# 如果WCF中指定的IP地址错误(尽管IP地址正确),则TCP错误

C# 如果WCF中指定的IP地址错误(尽管IP地址正确),则TCP错误,c#,wcf,C#,Wcf,我有一个承载WCF服务的应用程序。 我正在通过BackgroundWorker private bool isConnected; private BackgroundWorker asyncWorker = new BackgroundWorker(); InitializeComponent(); asyncWorker.WorkerReportsProgress = true; asyncWorker.WorkerSupportsCancellat

我有一个承载WCF服务的应用程序。 我正在通过
BackgroundWorker

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();
    }
和嫁妆:

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
}
private void bwancy\u DoWork(对象发送方,DoWorkEventArgs e)
{
BackgroundWorker BWANC=发送方作为BackgroundWorker;
尝试
{
如果(!未连接)
{
//返回IP地址配置的列表
IPHostEntry ips=Dns.GetHostEntry(Dns.GetHostName());
//获取计算机IP地址
IPAddress _IPAddress=IPAddress.Parse(tbServerIp.Text);
//创建指定服务启动位置所需的url
urlService=“net.tcp://”+_ipAddress.ToString()+“:8000/MyService”;
//指示ServiceHost使用的类型是ServiceLibrary.service1
//主机=新的ServiceHost(typeof(ServiceLibrary.service1));
ServiceLibrary.service1 serviceInstance=新的ServiceLibrary.service1();
serviceInstance.CapturingEvent+=您的serviceInstance\u StartCapturingEvent;
serviceInstance.OnProcessExitedEvent+=serviceInstance\u OnProcessExitedEvent;
主机=新的ServiceHost(serviceInstance);
host.Opening+=新的事件处理程序(host\u Opening);
host.Opened+=新的事件处理程序(host\u已打开);
host.Closing+=新的事件处理程序(host\u Closing);
host.Closed+=新的事件处理程序(host\u Closed);
//在绑定中,我们可以选择要使用的传输层。HTTP、TCP等。
NetTcpBinding=新的NetTcpBinding();
tcpBinding.TransactionFlow=false;
tcpBinding.Security.Transport.ProtectionLevel=System.Net.Security.ProtectionLevel.EncryptAndSign;
tcpBinding.Security.Transport.ClientCredentialType=TcpClientCredentialType.Windows;

tcpBinding.Security.Mode=SecurityMode.None;//首先不要使用IP地址,除非你只是做
localhost
dev,使用DNS名称或主机文件名条目总是一个坏主意。其次,我假设你的
host
变量是一个类成员变量(上面没有包含的代码)。打开主机后,它的绑定将在服务器内存中保持活动状态,直到重新启动应用程序(这是标准做法)

另一个问题是,在代码< >代码> BasyCycDoWork < /Code >块中,在单击表单按钮后关闭主机,但不使用更新的表单数据重新绑定/重新打开主机。请考虑以下事项来修复此问题。

  • 将执行实际主机绑定的代码从
    bwancy\u DoWork
    移到自己的方法中
  • bwancy\u 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;
    }
    

    您能告诉我如何使用DNS名称或主机文件名条目吗?顺便说一句,在插入错误的ip地址并重新插入正确的ip地址后,我仍然收到相同的错误