Tuesday, November 28, 2006

信道"tcp"已注册??

刚才在写一个remoting的程序,但在执行的时候会报异常:信道"tcp"已注册。


代码片断:

BinaryServerFormatterSinkProvider provider = new BinaryServerFormatterSinkProvider();
provider.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;


Hashtable props = new Hashtable();


props["port"] = 7654;
//props["name"] = "TcpChannel";


TcpChannel _chanl = new TcpChannel(props, null, provider);


//Console.WriteLine("Channel's Name:" _chanl);


Console.WriteLine("Register TcpChannel...");
ChannelServices.RegisterChannel(_chanl, false);


RemotingConfiguration.RegisterWellKnownServiceType(typeof(CRBTGateWay4Center), "CRBTGateway4Center",
WellKnownObjectMode.Singleton);

在各网站狂找原因和解决方法,最后才搞明白。

不是说注册信道的端口被占用了,而是这个信道的名字已经被占用了。即:异常中的"tcp"是要注册信道的名字。可以在控制台上打印信道名字看出来。其实这个"tcp"是.Net默认的名字,如果你没有指定的话。


那么我们为信道赋予其他的名字好了,TcpChannel 有一个ChannelName的属性,试了一下不行,这是个只读属性。那么怎么指定名字呢?


先从TcpChannel 的构造函数入手:


public TcpChannel (
IDictionary properties,
IClientChannelSinkProvider clientSinkProvider,
IServerChannelSinkProvider serverSinkProvider
)


参数



properties


一个 IDictionary 集合,它为客户端和服务器信道要使用的配置属性指定值。


clientSinkProvider


客户端信道要使用的 IClientChannelSinkProvider 实现。





serverSinkProvider


服务器信道要使用的 IServerChannelSinkProvider 实现。




看来我可以通过properties来干,我用的Hashtable类型的 props 就是第一个参数,而我用的信道类型是TcpChannel,它所支持的信道属性有:









TcpChannel



authorizationModule


bindTo


exclusiveAddressUse


impersonate


machineName


name


port


priority


rejectRemoteRequests


secure


servicePrincipalName


suppressChannelData


timeout


tokenImpersonationLevel


useIpAddress



参见:http://msdn2.microsoft.com/zh-cn/library/kw7c6kwc(VS.80).aspx


呵呵,看到黑体的port属性了吗,我在代码里设置了它props["port"] = 7654;


那个斜体的name 属性就可以指定信道的名字,那么可以用同样的方法props["name"] = "TcpChannel";


把这行代码加进去试一下(上面的代码中注释掉的),OK了!






Technorati : , ,

No comments: