0

我设置了一个 TCP 应用程序,以便服务器和客户端使用已由 BinaryFormatter 序列化然后使用 Base64 编码的序列化对象进行通信。这是转换为字符串(用于跨流发送)和转换为对象(用于从流接收)的代码。

    private string SerializeObject(object obj)
    {
        using(var memStream = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(memStream, obj);
            memStream.Flush();
            memStream.Position = 0;

            return Convert.ToBase64String(memStream.ToArray());
        }
    }

    private object DeserializeStream(string str)
    {
        try
        {
            using (var memStream = new MemoryStream(Convert.FromBase64String(str)))
            {
                var formatter = new BinaryFormatter();
                memStream.Seek(0, SeekOrigin.Begin);

                return (object)formatter.Deserialize(memStream);
            }
        }
        catch (SerializationException e) { OutputError(e); return null; }
        catch (DecoderFallbackException e1) { OutputError(e1); return null; }
        catch (FormatException) { return null; }
    }

当我收到数据时,我会这样做:

StreamReader r = new StreamReader(cli.GetStream());
string str = r.ReadLine(); 
if ((str == "") || (str == null)) 
{ 
    ShutdownClient(-2); 
}
else
{
    object o = DeserializeStream(str);
    if (o == null)
    { ResendLastPacket(); }
    else 
    { ParsePacket(o); }
}

编辑:这是发送方法

        public void Send(Packet packData)
        {
            try
            {
                StreamWriter w = new StreamWriter(clientObject.GetStream());
                w.WriteLine(SerializeData(packData));
                w.Flush();
            }
            catch (NullReferenceException) { }
            catch (IOException) { CloseObject(); }
        }

其中 Packet 是具有 [Serializable] 的自定义对象。clientObject 是一个 TcpClient。

现在,当我在同一台机器上启动客户端和服务器时,程序通常可以正常工作。没有任何错误。但是,如果我将客户端应用程序传输到远程 PC 并从那里使用它,我主要会得到 FormatExceptions。主要是错误:

"The input stream is not a valid binary format. The starting contents (in bytes) are: 6D-2E-44-72-61-77-69-6E-67-2E-43-6F-6C-6F-72-0F-00 ..."

我在这里做错了什么?或者我可以使用什么来代替它作为更有效的选择?

4

0 回答 0