使用SoapFormatter时XML响应无效
本文关键字:响应 无效 XML SoapFormatter 使用 | 更新日期: 2023-09-27 18:27:47
长话短说,我的应用程序一直在使用二进制串行化在服务器/客户端之间发送原始文本和图形。为了在同一个端口上推送这两个项,我尝试更改为使用Soap格式化程序发送一个带有类型标志的对象和稍后要强制转换的包含对象。我尝试将一个字符串包装在SoapFormatter中,并使用SoapFormatter对对象进行序列化和反序列化。当我尝试这样做时,客户端在反序列化对象时抛出异常:"给定编码中的无效字符。第1行,位置6。"你知道我做错了什么吗?
通过网络发送的对象:
[Serializable]
public class NetContainer
{
//this object is sent and can contain either Text or an Image file
#region Variables
private Flag flag; //type of object being sent
private object media;
#endregion Variables
#region Constructor
public NetContainer(Flag type, object containedObject)
{
flag = type;
media = containedObject;
}
#endregion Constructor
#region Properties
public Flag Flag
{
get { return flag; }
set { flag = value; }
}
public object Media
{
get { return media; }
set { media = value; }
}
#endregion Properties
}
public enum Flag
{
Imain,
IProfile,
TMain,
ABack
}
发送代码:
public void SendText(string text)
{
//assemble package
NetContainer package = new NetContainer(Flag.TMain, text);
foreach (TcpClient clientInstance in ClientList)
{
if (clientInstance.Connected) //if connection is active
{
BinaryFormatter formatter = new BinaryFormatter();
//serialize package and send
formatter.Serialize(clientInstance.GetStream(), package);
}
}
}
引发异常的接收代码:
private void StartReading()
{
while (connection.Connected == true)
//while (true)
{
using (NetworkStream stream = connection.GetStream()) //use the client's connection stream
{
//BinaryFormatter formatter = new BinaryFormatter();
SoapFormatter formatter = new SoapFormatter();
while (true)
{
//deserialize the package from the network stream
NetContainer package = (NetContainer)formatter.Deserialize(stream);
switch (package.Flag)
{
case Flag.TMain:
rtbMain.Text += (string)package.Media;
break;
case Flag.Imain:
pbxMain.Image = (Image)package.Media;
break;
default:
Console.WriteLine("Unkown Flag error: " + package.Flag);
break;
}
}
}
}
}
问题已解决。我不知怎么离开了电话:
BinaryFormatter formatter = new BinaryFormatter();
需要:
SoapFormatter formatter = new SoapFormatter();