我正在尝试创建一个在线Checkers游戏,开始学习网络。我有一个服务器/客户端架构,我正在使用TCP套接字。
我想通过流发送自定义object
。我使用XML序列化系统来做到这一点,一切似乎都工作,直到客户端需要反序列化"序列化"来自服务器的消息。达到此点后,我收到此错误:
XmlException:未显示文档元素。第1行,第1位。 Mono.Xml2.XmlTextReader.Read() System.Xml.XmlTextReader.Read() System.Xml.XmlReader.MoveToContent()System.Xml.Serialization.XmlSerializationReaderInterpreter.ReadRoot() System.Xml.Serialization.XmlSerializer.Deserialize(System.Xml.Serialization.XmlSerializationReader reader)
这是我用来序列化对象的函数:
private string Serialize(List<PieceInfo> pieces)
{
StreamWriter stWriter = null;
XmlSerializer xmlSerializer;
string buffer;
try
{
xmlSerializer = new XmlSerializer(typeof(List<PieceInfo>));
MemoryStream memStream = new MemoryStream();
stWriter = new StreamWriter(memStream);
XmlSerializerNamespaces xs = new XmlSerializerNamespaces();
xs.Add("", "");
xmlSerializer.Serialize(stWriter, pieces, xs);
buffer = Encoding.ASCII.GetString(memStream.GetBuffer());
return buffer;
}
catch (Exception Ex)
{
throw Ex;
}
}
这是我用于反序列化的函数:
public List<PieceInfo> DeSerialize(string xmlString)
{
XmlSerializer xmlSerializer;
MemoryStream memStream = null;
try
{
xmlSerializer = new XmlSerializer(typeof(List<PieceInfo>));
byte[] bytes = new byte[xmlString.Length];
Encoding.ASCII.GetBytes(xmlString, 0, xmlString.Length, bytes,0);
memStream = new MemoryStream(bytes);
memStream.Seek(0, SeekOrigin.Begin);
object objectFromXml = xmlSerializer.Deserialize(memStream);
List<PieceInfo> pieces = (List<PieceInfo>)objectFromXml;
return pieces;
}
catch (Exception Ex)
{
throw Ex;
}
}
发送消息代码:
StreamWriter writer = new StreamWriter(tcpClient.GetStream());
writer.WriteLine("GRABB~"+ Serialize(ListPiecesForSerilization));
writer.Flush();
接收消息代码:
private void OnIncomingData(string data)
{
string[] lines;
lines = data.Split('~');
for (int i = 0; i != lines.Length; i++)
{
switch (lines[i])
{
case "GRABB": // get board's current condition
List<PieceInfo> pieces = DeSerialize(lines[i+1]);
board.SetPiecesPosition(pieces);
break;
}
//Debug.Log(data);
}
}
PieceInfo
课程,包含有关作品的基本信息:
[Serializable]
public class PieceInfo
{
public int xPos;
public int zPos;
public bool isWhite;
public bool isKing;
public void SetPieceInfo(int x, int z, bool c, bool k)
{
xPos = x;
zPos = z;
isWhite = c;
isKing = k;
}
}
班级PieceInfo
标有属性[Serializable]
,但我没有在其中设置任何其他属性。
我使用string
和NetworkStream
/ StreamWriter
以StreamReader
发送xml邮件。
当我尝试反序列化消息时,为什么会出现错误?
答案 0 :(得分:0)
问题是我使用StreamWriter.WriteLine
和StreamReader.ReadLine()
没有写/读孔xml文件。我在循环中使用了StreamReader.Read()
,直到我为&#34; end-of-file
&#34;设置为标记的符号为止。满足了。