Remoting在Internet环境下的测试
朱二(2008.10,转载请保留作者)
分两种情况:单向通道和双向通道
在单向通道(Client->Server)情况下,分两种情况:
A、Server在内网,则需要在路由器上建立端口映射,同时在Server建立通道的时候,指定路由器IP地址
B、Server在公网,不需要任何设置
在双向通道(Client<->Server)情况下
Server和Client都具有双重角色,都可作为客户端和服务端,因此可等同对待。
无论哪一方在内网,都需要建立端口映射,并且在建立通道的时候,指定路由器IP地址。
相关代码:
跨路由访问内网远程服务端的问题
比如远程服务端的内网地址为192.168.0.8,端口为8888,在路由器地址为11.11.11.11,在路由器上添加端口映射,将路由器端口8888映射至192.168.0.8的端口8888
远程类型为:
- Public Class CRemotingLib
- Inherits MarshalByRefObject
- Public Function Test() As String
- Return Now.ToString()
- End Function
- Public T As New CTest
- End Class
- Public Class CTest
- Inherits MarshalByRefObject
- Public Function Test() As String
- Return Now.ToString()
- End Function
- End Class
客户端代码为
- Dim objectUrl As String = String.Format("tcp://{0}:{1}/CRemotingLib.rem", "11.11.11.11",8888)
- Dim root As RemotingHttpTest.CRemotingLib = Activator.GetObject(GetType(RemotingHttpTest.CRemotingLib), objectUrl)
- Console.WriteLine(root.Test())'正常
- Console.WriteLine(root.T.Test())'异常,不能正常执行,调试发现,客户端执行次句时会连接192.168.0.8:8888
解决办法:
服务端设置信道属性时使用路由器的IP地址
- Dim cbin As BinaryClientFormatterSinkProvider = New BinaryClientFormatterSinkProvider()
- Dim sbin As BinaryServerFormatterSinkProvider = New BinaryServerFormatterSinkProvider()
- sbin.TypeFilterLevel = Runtime.Serialization.Formatters.TypeFilterLevel.Full
- Dim properties As IDictionary = New Hashtable()
- properties("port") = 9111
- properties("machineName") = "11.11.11.11" '注意这一句,Server将IP地址指定为路由器地址,这样客户端会在后继调用时使用此地址连接Server
- Dim channel As TcpChannel = New TcpChannel(properties, cbin, sbin)
- ChannelServices.RegisterChannel(channel, False)
- RemotingConfiguration.RegisterWellKnownServiceType(GetType(RemotingHttpTest.CRemotingLib), "CRemotingLib.rem", WellKnownObjectMode.Singleton)