解决.Net Remoting无法传Stream类型参数的问题

 

利用.Net Remoting传Stream类型参数时,一般会报下面两个错误。

1.如果是用TcpServerChannel(string name, int port);或是TcpServerChannel(int port);注册通道的话,会报下面这个错误:System.Runtime.Serialization.SerializationException: Because of security restrictions, the type System.Runtime.Remoting.ObjRef cannot be accessed. ---> System.Security.SecurityException: Request failed.

2.如果是用TcpServerChannel(IDictionary properties, IServerChannelSinkProvider sinkProvider);或是

TcpServerChannel(IDictionary properties, IServerChannelSinkProvider sinkProvider, IAuthorizeRemotingConnection authorizeCallback);或是

TcpServerChannel(string name, int port, IServerChannelSinkProvider sinkProvider);注册通道的话,会报下面这个错误:System.Runtime.Remoting.RemotingException was unhandled by user code
  Message="This remoting proxy has no channel sink which means either the server has no registered server channels that are listening, or this application has no suitable client channel to talk to the server."

经过这两天的研究,暂时没有找到传Stream的解决方案。目前可以使用如下替代方法解决这个问题:

客户端使用序列化的byte[]类型替代Stream来作为参数与服务器进行通信。代码如下:

客户端:

public static void WriteFileToDBByStream(Stream stream) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); IFormatter formatter = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(); formatter.Serialize(memoryStream, buffer); remotingInterfaceInstace.WriteFileToDBByStream(memoryStream.ToArray()); }

服务端:

public void WriteFileToDBByStream(byte[] streamBytes) { IFormatter format = new BinaryFormatter(); MemoryStream memoryStream = new MemoryStream(streamBytes); byte[] data = format.Deserialize(memoryStream) as byte[]; memoryStream = new MemoryStream(data); //使用Stream UserDefinedFunction(memoryStream); }

把Stream先转化为byte[]传送,服务端再把byte[]转化为Stream。

但是令我不解的是,如果服务端把Stream作为.Net Remoting的返回值,就不报错,而且结果也成功。如果有知道原因的朋友,请给我留言,谢谢。

你可能感兴趣的:(.net,Stream,properties,application,buffer,byte)