这里我有一个我为了通过串口发送文本文件和图像而创建的类:
public class SendItem
{
private byte[] bytes;
private string _fileName;
private string _extension;
private int bytesSin;
public string Extension
{
get { return _extension; }
set { _extension = value; }
}
public string FileName
{
get { return _fileName; }
set { _fileName = value; }
}
public byte[] Bytes
{
get { return bytes; }
set { bytes = value; }
}
public SendItem()
{
}
public void SendFile(SerialPort serialPort1)
{
if (serialPort1.IsOpen)
{
OpenFileDialog OFDialog = new OpenFileDialog();
OFDialog.Title = "Open File";
OFDialog.Filter = "Text Files (*.txt)" + "|*.txt|All files (*.*)|*.*";
OFDialog.InitialDirectory = @"C:\";
bool? userClickedOK = OFDialog.ShowDialog();
if (userClickedOK == true)
{
serialPort1.DiscardInBuffer();
string chosenFile = OFDialog.FileName;
string ext = Path.GetExtension(OFDialog.FileName);
_extension = ext;
byte[] data = File.ReadAllBytes(chosenFile);
SendItem newSendItem = new SendItem();
newSendItem._extension = ext;
newSendItem._fileName = System.IO.Path.GetFileNameWithoutExtension(chosenFile);
newSendItem.bytes = data;
byte[] view = newSendItem.Serialize();
string test = Convert.ToBase64String(data);
serialPort1.Write(newSendItem.Serialize(), 0, newSendItem.Serialize().Length);
//serialPort1.Write(data, 0, data.Length);
}
}
}
public override string ToString()
{
return string.Format("File: {0}{1}",_fileName, _extension);
}
}
SendFile方法中存在相当多的冗余,但我要求它会被忽略,以支持我继续使用的以下问题。
每当我从文本框发送文本文件或纯文本聊天文本时,都会执行以下代码块而不会触发捕获:
void _sPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
byte[] data = new byte[sp.BytesToRead];
string message = string.Empty;
sp.Read(data, 0, data.Length);
try
{
SendItem receivedObject = data.Deserialize<SendItem>();
File.WriteAllBytes(@"d:\" + receivedObject.FileName + receivedObject.Extension, receivedObject.Bytes);
message = "File has been recieved.";
sp.Write("File sent.");
}
catch (Exception exp)
{
errors = exp.Message;
message = Encoding.UTF8.GetString(data);
}
App.Current.Dispatcher.Invoke(new Action(() => _response.Add("Friend: " + message)));
}
当我尝试发送图像时出现问题...它触发catch并提供异常XML文档中存在错误(5,3870)。
我写的序列化器和解串器如下:
public static byte[] Serialize<T>(this T source)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
serializer.Serialize(stream, source);
byte[] buffer = stream.GetBuffer();
stream.Close();
return buffer;
}
public static T Deserialize<T>(this byte[] source)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
MemoryStream stream = new MemoryStream(source);
T result = (T)serializer.Deserialize(stream);
stream.Close();
return result;
}
有谁可以指出我犯错误的地方?我已经调试了很多年了,我无法绕过它。
**编辑: 我还包括我试图发送的图像的序列化数据,看了之后,看来我的字节对于串口来说可能太大了 - 有没有办法调整这个或允许串口取所有的发送的数据?
/ 9J / 4AAQSkZJRgABAgAAAQABAAD // gAEKgD / 4gIcSUNDX1BST0ZJTEUAAQEAAAIMbGNtcwIQAABtbnRyUkdCIFhZWiAH3AABABkAAwApADlhY3NwQVBQTAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA9tYAAQAAAADTLWxjbXMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAApkZXNjAAAA / AAAAF5jcHJ0AAABXAAAAAt3dHB0AAABaAAAABRia3B0AAABfAAAABRyWFlaAAABkAAAABRnWFlaAAABpAAAABRiWFlaAAABuAAAABRyVFJDAAABzAAAAEBnVFJDAAABzAAAAEBiVFJDAAABzAAAAEBkZXNjAAAAAAAAAANjMgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB0ZXh0AAAAAEZCAABYWVogAAAAAAAA9tYAAQAAAADTLVhZWiAAAAAAAAADFgAAAzMAAAKkWFlaIAAAAAAAAG + iAAA49QAAA5BYWVogAAAAAAAAYpkAALeFAAA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kcnX5aaPqPzb6xx + hHXmAAAAAsqBBFtSoEAQFQSVKAAAsFAFASXCMdWeGbiM3T5 / f5zp6iXXQhalGGYwti0AJRDxvZ8evj / rfmvvLy9Uu + MAAAAAsFSpFAQABFEBIS0AACWGQAoIxwzwjXjnM3Wzi8vn + j5s36qXXaBQARKUCxZAR5Hr + Rb8z97 + dfaOX0Vl6cIFAAAAFJYKgqVAgACKMFSkoAAlFY5AAgxsjGZM3GWry8ffxze + VrtFEUQAAKsJUsPI9fy Q + M + N + X9jXL9CuOV4wUAAAAsAAoEgAAAGFiWygAACZQVKiCyWZRZLFGnk7edrC + X8w9H3j852an6C + bxxr6afN7D6B4 / bHW59yZTDmOp4 / CfTeT43RqeN6HD6u8febIvAKAAAAAFJZUCAAACDES2WFSgBKTLGiwCRFkosQpjMh8l4H0fDn0 / Nehwe50xz6PT0Z6eZr9nk1Nfs + NlNfT7vM7OTHwXL1mjX27948 / 0MfRjwvrPkfv5n3BriVZAopAAALKkpAAAAEpbgmWUAsoShKSwUCURUSgBKHF5nv + Hy6的/ F +3瓦特+ trpweZ9pyx4XF9bq1n5 + / RbJt2bts5 / B8f0fJvp8 / 2eznceL7k7sX5L9J + C + 4Z7S9eIJBVEQWikUkpAAABKSyhLWBM2gqQqwFIUAFIUlKlIgp819L5kvz / bo18fV9Ew3Xj5 + v15XH0Z60zz15acpv5a8nm + hmnmb + njy8P6bxPct9Kx6PPRAAEVQQIVKCCygEUAEpgJZYKAAlAGWNRZQQotIAGrdjHy / nbuPn6Po + 3wfWznuapvKcvTm7ctDU16tnPjXo3h3pPJ6PFuur2 /升/ oNZ + hS9OQiZQKgqCoKgWBYFgBbAsEEXEQAAqFAAsFCCkFoAhRJ8x4 / 1PhcvRwe38t6ur9BePt5TL436PwOl6NXlYbdnofP91n2nPz3heLyenye09z6j5j62Y9Ea5CqS2BKFBAAUAAEBQAGsQBUoBUFAlJUW2xIKQKFAeV819P8xz6 + P0XRrfqavKwj3 / P5s16NGVrg6ZLnq2ePnG7Vs3Wer9V8P9VMe + S81lWwAFgsCoAKgAVCoFlGNGCBUFCoKBZUJVlxyqyyS2AAS2zHwo2eBhw57dnldXntze26x6no + dv5dO3R5c1OzkVfJ5O + dOfN382s + GY + U9LOf0vo / PPeZ + lcnXcyiRYqwVAoERUFgWBYtEsEprS0lhklJQURcaoIsoBUhlNfkL7Pk / O + a37Pl + RorbpNT03H6 OOurZr0ntbfIyzeycuxNuGnVb06efOzPy / S8vWIjWM + vip7 / P / H7M39E9n8v2n6i + H + nmfQVElARKhYogLIZSoJSVKxhVgVKLBbCAUEqkmOlc / H5vkl9jg8vVddPNi1KhAq9vBsl9HCY56btGrXZumqp046Kt36tKXQXIWAluI2Z6Kd3b42Uv6F9L + Rfex78yxzEWICZYiglgsQyRFxyhjY1FlIFoSgASwyjUuHF1eFm / OeRnp60hFkMoVUAhlt57L0YMJWWpZta8TdqgCxYMmNBEqFyuNTPs4afrXd + cfpGWMymEBLAIVKEsCFxzxIl1CVQRYKsKgWBo26Jdfyn0 / wU35WNx65rEqwlSgUlglRACAFRVQUIAQWC241Llhkuz9M / MPpJP0WZY4QkkosWAFxsKiLAljUmWNWpUJRZQlBDHRt0y8H579j8RrWvG46lsFbequF62B5j07J5c9XBfOnpLPMdkOSdkl5Has4naOK9mRwvTHmPR1HE3ajELYiZZYZLl08mcfs2Xk + rmJZmLiWy4lISkACmA1FgtgJS3FbbBYkmrTt5835D5j0 / L6akssAZY09PzeziKQuWHZW3i2c6d / B18q4ki9nF6Fmvk2aoZY1ero4MU9rW85NunVLUsUItgyywyPvvrPhfusyQzIUhFWUkIygEyNdjapZFgoJlFLLCIujl6vOy / POXPX1ogsKybE6eTfsrlwysYbcZXZwdNTPi261xlRM8Ok6fP6uUgq3HI9LzvT8xJjYSEtsFSlyxp9T + hfm36RmSS5kuIyiKsCWCxFiBLsssgAluSCkkyxsOfwvc + czfhpZ1qCiGzZpqdDRsrPbpyM7q3
答案 0 :(得分:1)
它可能是也可能不是整个问题,但这肯定是 问题:
byte[] buffer = stream.GetBuffer();
这很可能会返回比你想要的更多的数据 - 因为它并不局限于流的长度。 MemoryStream
有一个方便的MemoryStream.ToArray
方法来简化:
public static byte[] Serialize<T>(this T source)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
MemoryStream stream = new MemoryStream();
serializer.Serialize(stream, source);
return stream.ToArray();
}
(关闭您创建的MemoryStream
没有任何好处 - 如果 认为您需要,则应使用using
语句。 )
同样,您的Deserialize
方法可以简化为:
public static T Deserialize<T>(this byte[] source)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T) serializer.Deserialize(new MemoryStream(source));
}
鉴于您有效地尝试反序列化“XML文档 - 然后可能是一堆”空白“数据,这可能就是问题。
编辑:现在还有第二个问题:
byte[] data = new byte[sp.BytesToRead];
string message = string.Empty;
sp.Read(data, 0, data.Length);
您假设所有数据都可以一次性读取。如果数据多于串行端口的缓冲区大小,则情况并非如此。相反,如果你试图将多个“消息”放到有效的流上,你需要 指示消息的结束(并在你找到之前继续阅读)或写消息本身之前的消息长度 - 然后在读取时读取该长度,然后确保读取那么多字节。
当您尝试将面向流的协议用作面向消息的协议时,这是一个标准问题。
答案 1 :(得分:-1)
您应该使用ToByteArray()
代替GetBuffer()
。