首页 > 解决方案 > 调用后.net远程关闭与服务器的连接

问题描述

我对 .NET 远程处理非常陌生。我们有一个使用 TCP 连接(.NET 远程处理)调用 Windows 应用程序的 MVC 网站。每 30 秒运行一个计时器,通过 TCP 进行调用,但完成后,连接仍保持建立。结果,几天后,服务器抛出异常,因为所有端口都用完了。然后我们必须重新启动应用程序池才能解决问题。我不确定我们如何在使用后关闭端口,以便我们可以再次使用它。我们的网站有很多用户。

下面是注册频道的客户端代码

        bool Registered = false;

        foreach (IChannel ic in ChannelServices.RegisteredChannels)
        {
            if (ic.ChannelName == ChannelNameRemoting)
            {
                return ic;
            }
        }

        // Channel not found yet


        IDictionary channelConfig = new Hashtable();
        channelConfig["name"] = ChannelNameRemoting;
        channelConfig["secure"] = false;

        BinaryClientFormatterSinkProvider defaultClientSink = new BinaryClientFormatterSinkProvider();

        if (remotingSinkProvider == null)
        {
            remotingSinkProvider = new CustomClientChannelSinkProvider();

            remotingSinkProvider.EncodingDecodingProviderEvent
                += new CustomClientChannelSinkProvider.EncodingDecodingProviderDelegate(remotingSinkProvider_EncodingDecodingProviderEvent);
        }

        defaultClientSink.Next = remotingSinkProvider;

        IChannel channel = new TcpChannel(channelConfig, defaultClientSink, null);

        if (!Registered)
        {
            ChannelServices.RegisterChannel(channel, false);

        }

        return channel;

下面的调用将创建一个连接以在计时器中连接到服务器。

var connection = (testConnect)Activator.GetObject(
                                      typeof(testConnect),
                                      "tcp://" + _remotingUrl + ":" + _remotingPort + "/test/test4"
                              );

connection.FunctionCall();

在此处输入图像描述

标签: c#.net.net-remoting

解决方案


我想您需要取消注册您的频道。请检查链接

所以最终我们创建实例TcpChannel并注册到通道服务,最后返回给父方法,这样就可以使用和调用了。在您拥有返回通道实例的方法的文件/类中,还应该有另一种方法来取消注册 tcp 通道,一旦完成调用,您需要调用这个新方法来取消注册通道,这将关闭连接。

public void UnregisterMyTcpChannel(TcpChannel yourChannelInstance)
{
   ChannelServices.UnregisterChannel(yourChannelInstance);
}

推荐阅读