我目前正在使用套接字尝试在Silverlight 3客户端和.NET3.5服务之间发送消息。我可以很好地设置TCP连接,并发送数据,但我的问题是序列化和反序列化DataContracts。
目前我们正在使用WCF PollingDuplex绑定来完成这项工作,但我们对它的性能不满意,所以尝试使用套接字,同时仍尝试使用DataContract属性。我的代码如下:
// Client
public void Send(ActionMessage actionMessage)
{
DataContractSerializer dcs =
new DataContractSerializer(actionMessage.GetType());
MemoryStream memoryStream = new MemoryStream();
dcs.WriteObject(memoryStream, actionMessage);
byte[] sendBuffer = new byte[4096];
memoryStream.Position = 0;
memoryStream.Read(sendBuffer, 0, sendBuffer.Length);
SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs();
socketAsyncEventArgs.SetBuffer(sendBuffer, 0, sendBuffer.Length);
if(!_socket.SendAsync(socketAsyncEventArgs))
HandleSendComplete(socketAsyncEventArgs);
}
// Service
private byte[] _recieveBuffer = new byte[4096];
private int _receivedLength;
private void socket_OnReceiveComplete(IAsyncResult asyncResult)
{
_receivedLength += _tcpClient.Client.EndReceive(asyncResult);
// See if there's more data that we need to grab
if (_receivedLength < _recieveBuffer.Length)
{
// Need to grab more data so receive remaining data
_tcpClient.Client.BeginReceive(_recieveBuffer, _receivedLength,
_recieveBuffer.Length - _receivedLength, SocketFlags.None,
new AsyncCallback(socket_OnReceiveComplete), null);
return;
}
MemoryStream memoryStream = new MemoryStream();
memoryStream.Position = 0;
memoryStream.Write(_recieveBuffer, 0, _recieveBuffer.Length);
DataContractSerializer dcs = new DataContractSerializer(typeof(ActionMessage));
object o = dcs.ReadObject(memoryStream);
ActionMessage actionMessage = (ActionMessage) o;
}
抛出XmlException的ReadObject行:Unexpected End of File。我已经尝试了各种各样的事情,包括在收到时从字节数组(_recieveBuffer)截断尾随0,在结尾处只留下一个0等,但似乎没有任何效果。我检查了客户端和服务器端的byte []缓冲区,它们在开头和结尾都有相同的值,并且长度相同。我也尝试使用actionMessage.GetType()和typeof(ActionMessage)作为DataContractSerializer的参数,但没有区别......
我在这里搞错了:为什么dataContractSerializer.Write()不接受dataContractSerializer.Read()生成的输出?
我有一个美好的一天,直到达到这个...我确实找到另一个有相同问题的人,但提供的解决方案,在服务端设置memoryStream.Position = 0不起作用...
提前致谢。
答案 0 :(得分:0)
如果我不得不猜测,我会说你的memoryStream.Position = 0;线路在错误的位置。
将缓冲区写入流后,您需要重置流中的位置。