开发者

problem with sending serialized object over tcpclient

开发者 https://www.devze.com 2023-01-23 11:29 出处:网络
I am trying to send an object over tcpclient from the server to a client and i get an error . First, here is the pack class :

I am trying to send an object over tcpclient from the server to a client and i get an error . First, here is the pack class :

[Serializab开发者_开发问答le()]
    public class pack
    {
        public int a;
    }

here is the server's sending code(it's namespace is WindowsFormsApplication1) :

                pack pachet = new pack();
                pachet.a = 3;
                IFormatter bformatter = new BinaryFormatter();
                NetworkStream ntstream = tcpClient.GetStream();
                bformatter.Serialize(ntstream, pachet);

and the client's 'translation' code(it's namespace is WindowsFormsApplication2) :

            NetworkStream strm = client.GetStream();
            IFormatter bformatter = new BinaryFormatter();
            pack nettmp = (pack)bformatter.Deserialize(strm);

and the error is :

serializationException was unhandeled. Unable to find assembly 'WindowsFormsApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Can someone tell me what the problem is?


Well, as the error message says, your server can't find the WindowsFormsApplication1 assembly.

Do you have it on the client side? You won't be able to use binary deserialization if you don't have the all the assemblies containing the types to be deserialized.

Note that the namespaces are irrelevant - and you won't be able to deserialize an object just because you've got a type with the same name in a client assembly. The assembly name is embedded in the serialization data.

(Personally I'm not terribly keen on using the default .NET binary serialization to start with, as it's pretty fragile in terms of backward and forward versioning, but that's a different matter. If you're interested in alternatives, you might want to look at text based formats such as XML, YAML and JSON, or binary formats such as Thrift and Protocol Buffers.)


For this issue you need to compile and assemble a DLL Library, then add it as a reference to both projects. Just remember, all the classes in the DLL library must be [Serializable].


You need to add reference to WindowsFormsApplication1 to the client. Or better yet, add a separate assembly for classes which are common for both the client and the server.


I found a great tut on how to serialize by transforming an object first into an xml then into a string ! http://www.dotnetjohn.com/articles.aspx?articleid=173

0

精彩评论

暂无评论...
验证码 换一张
取 消