长话短说,我的应用程序一直在使用二进制serilization在服务器/客户端之间发送原始文本和图形。想要在同一个端口上推送这两个项目,我尝试更改为使用Soap格式化程序发送一个带有类型标志的对象,并包含稍后要转换的对象。我尝试在abject中包装一个字符串,并使用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;
}
}
}
}
}
答案 0 :(得分:1)
问题已解决。我不知何故离开了界限:
BinaryFormatter formatter = new BinaryFormatter();
需要:
SoapFormatter formatter = new SoapFormatter();