从服务器接收图像数据时出现随机错误
本文关键字:随机 错误 数据 服务器 图像 | 更新日期: 2023-09-27 18:23:51
我有一个C#应用程序。
它将图像上传到我的服务器,并在必要时下载。
这是我的客户:
sb.Clear();
sb.Append(GeneralTags.ACTION_ADD);
sb.Append(Shared.DLE);
sb.Append("GALLERY");
sb.Append(Shared.DLE);
sb.Append(Shared.CurrentClientId);
sb.Append(Shared.DLE);
sb.Append(JsonConvert.SerializeObject(gallery));
sb.Append(Shared.DLE);
byte[] byteArray = System.Web.HttpUtility.UrlEncodeToBytes(sb.ToString());
int packetCount = 0;
using (TcpClient clientSocket = new TcpClient())
{
clientSocket.Connect(GeneralTags.RASPBERRY_PI_IP_ADDRESS, GeneralTags.RASPBERRY_PI_PORT);
using (NetworkStream serverStream = clientSocket.GetStream())
{
serverStream.Write(byteArray, 0, byteArray.Length);
serverStream.Flush();
List<byte> requestInBytes = new List<byte>();
if (serverStream.CanRead)
{
int i = 0;
Byte[] bytesIn = new Byte[1024];
do
{
i = serverStream.Read(bytesIn, 0, bytesIn.Length);
byte[] receivedBuffer = new byte[i];
Array.Copy(bytesIn, receivedBuffer, i);
if (packetCount == 0)
{
packetCount = BitConverter.ToInt32(receivedBuffer, 0);
}
requestInBytes.AddRange(receivedBuffer);
} while (packetCount < requestInBytes.Count);
serverStream.Close();
var json = Encoding.UTF8.GetString(requestInBytes.ToArray(), 0, requestInBytes.ToArray().Length);
var galleryback = JsonConvert.DeserializeObject<Gallery>(json);
using (MemoryStream ms = new MemoryStream())
{
System.Diagnostics.Debug.WriteLine("BACK: " + galleryback.ImageData.Length.ToString());
ms.Write(galleryback.ImageData, 0, galleryback.ImageData.Length);
Shared.ViewImage(Image.FromStream(ms, true));
}
}
else
{
MessageBox.Show("Local Device Error");
}
}
}
这是我的类对象:
public class Gallery
{
public string Title { get; set; }
public string Description { get; set; }
public byte[] ImageData { get; set; }
public bool IsUploaded { get; set; }
public Int64 GalleryId { get; set; }
public string JobRef { get; set; }
}
如果我们假设我的服务器正在正确地发回整个数据阵列(我已经检查了从服务器发送的字节和我的客户端接收的字节)。。。
我得到这些类型的错误:
Unterminated string. Expected delimiter: ". Path 'ImageData', line 1, position 5515.
Unexpected character encountered while parsing value: �. Path '', line 0, position 0.
我该如何解决这个问题?
感谢
看起来您发送的是一个字节数组,其中序列化的JSON只是其中的一部分(您将其他内容附加到字符串中,如GeneralTags.ACTION_ADD
等),但当您收到数据时,您会尝试反序列化整个内容。当然,由于您没有JSON格式的数据,这导致DeserializeObject
无法解析传递给它的数据。您需要以某种方式提取序列化对象,例如使用regex或一些涉及子字符串的计算。