最近在用TCP写一个能够传输图片的服务器,但是却出现了这样一个问题,用电脑的时候图片可以完整的传输过去,服务器显示的数据没有问题,但是用移动端传输图片却发现服务器只能收到不到十分之一的数据,但是我感觉我写的逻辑没有问题,在pc端上也是一切正常的
这是我在PC端发送一个32k大小的图片服务器接收到的数据量
这是我打包到移动端发送同一张图片接收到的数据量
/// <summary>
/// 根据图片的路径返回图片的字节流 这是客户端发送图片的代码
/// </summary>
/// <param name="imagePath"></param>
/// <returns></returns>
public static byte[] GetImageByte(string imagePath)
{
FileStream files = new FileStream(imagePath, FileMode.Open);
byte[] imgByte = new byte[files.Length];
BinaryReader str = new BinaryReader(files);
files.Read(imgByte, 0, imgByte.Length);
files.Close();
//前缀
byte[] qzdataByte = Encoding.UTF8.GetBytes("01");
//前缀+图片数据
byte[] qzAndTexturedataByte = qzdataByte.Concat(imgByte).ToArray();
//图片数据长度
int imgdatalength = qzAndTexturedataByte.Length;
byte[] lengthimgdata = BitConverter.GetBytes(imgdatalength);
//数据长度+数据
byte[] newByte = lengthimgdata.Concat(qzAndTexturedataByte).ToArray();
return newByte;
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="msg"></param>
public static void SendMessage(byte[] msg)
{
clientSocket.Send(msg);
}
/// <summary>
/// 异步接收数据 这是服务器端接收数据的代码
/// </summary>
public void ReceiveMessageAsync()
{
if (clientSocket == null || clientSocket.Connected == false)
{
return;
}
clientSocket.BeginReceive(msg.Data, msg.StartIndex, msg.RemainSize, SocketFlags.None, ReceiveCallBack, null);
}
public void ReceiveCallBack(IAsyncResult ar)
{
try
{
if (clientSocket == null || clientSocket.Connected == false)
{
return;
}
int count = clientSocket.EndReceive(ar);
Debug.Log(count);
//客户端断开的时候会一直发送空数据
if (count == 0)
{
Close();
//clientSocket.Close();
}
msg.ReadMessage(count);
ReceiveMessageAsync();
}
catch (Exception e)
{
Debug.Log(e);
//clientSocket.Close();
Close();
}
}
/// <summary>
/// 数据解析
/// </summary>
public void ReadMessage(int newDataCount)
{
startIndex += newDataCount;
while (true)
{
//数据长度小于四个字节不进行解析
if (startIndex <= 4)
{
return;
}
counts = BitConverter.ToInt32(data, 0);
//Debug.Log("counts__" + counts);
//从4开始是因为0到3存储的是数据的长度
if ((startIndex - 4) >= counts)
{
string qz = Encoding.UTF8.GetString(data, 4, 2);
if (qz == "00")
{
s = Encoding.UTF8.GetString(data, 6, counts - 2);
}
else if (qz == "01")
{
MemoryStream fs = new MemoryStream();
fs.Write(data, 6, counts - 2);
img = Image.FromStream(fs);
Debug.Log(img);
//img.Save("F:\\UnityGongCheng\\ClientUpdate\\Assets\\Resources\\name.png", ImageFormat.Png);
//img.Save("D:\\Path\\name.png", ImageFormat.Png);
Debug.Log(a+b+".png");
img.Save(a+b+".png", ImageFormat.Png);
SendAndReceiveMessage.isTex = true;
Debug.Log("保存完毕!!!");
Debug.Log(SendAndReceiveMessage.isTex);
fs.Close();
}
//复制数组
Array.Copy(data, counts + 4, data, 0, startIndex - 4 - counts);
startIndex -= (counts + 4);
}
}
}