0
im trying to make a client and server that the server sends image to the client
到目前爲止,它可能只發送一個圖像和其他人的arent神祕的錯誤 接受我試圖找出錯誤,但沒有運氣... 這是服務器代碼: 公共無效SendImage(圖像張圖片) {C#TCP客戶端發送圖像/服務器
TcpClient tempClient = _Client;
if (tempClient.Connected) //If the client is connected
{
NetworkStream stream = tempClient.GetStream();
Bitmap bmp = new Bitmap(img);
BinaryWriter bw = new BinaryWriter(stream);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] buffer = ms.ToArray();
byte[] lengthbts= Get8LengthByte(buffer);
stream.Write(lengthbts,0,8);
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
// bw.Close();
}
}
byte[] Get8LengthByte(byte[] bytes)
{
string length = bytes.Length.ToString();
while (length.Length < 8)
{
length = "0" + length;
}
return Encoding.Default.GetBytes(length);
}
,這是客戶機代碼
NetworkStream stream = client.GetStream();
//Bitmap bmp = new Bitmap(img);
BinaryReader br = new BinaryReader(stream);
byte[] datalen = new byte[8];
br.Read(datalen, 0, 8);
string lenStr = (Encoding.Default.GetString(datalen));
int len = int.Parse(lenStr);//BitConverter.ToInt32(datalen, 0);//
Console.WriteLine(len);
byte[] buffer = new byte[len];
br.Read(buffer, 0, buffer.Length);
MemoryStream ms = new MemoryStream(buffer, 0, buffer.Length);
ms.Position = 0;
Image img = Image.FromStream(ms);
Invoke(new MethodInvoker(delegate()
{
pictureBox1.Image = img;
}
));
的想法是先發送圖片字節長度爲8字節長度爲 例如字節長度爲10則8字節長度爲「00000010」 接收到的第一個圖像非常好並且快速 但是第二個返回一個錯誤,可以使8字節長度爲整數字節[]收到更像「/// ???」和類似的東西,如果有人可以幫助我的數字出來,我將非常感激
非常感謝你,它可能工作流didnt讀取整個圖像字節和missedmuch它的謝謝! –