2013-07-25 87 views
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字節長度爲整數字節[]收到更像「/// ???」和類似的東西,如果有人可以幫助我的數字出來,我將非常感激

回答

1

這很難說。有一件事我可以建議是:如果你得到的長度值正確,該文件是大> 4K,那麼你應該繼續讀,直到長完成, 例如:

int offset=0; 
int bLeft=len; 
byte[] buffer = new byte[len]; 
while (bLeft > 0) 
{ 
    int ret = br.read(buffer, offset, bLeft); 
    if (ret > 0) 
    { 
     bLeft-=ret; 
     offset+=ret; 
    } 
    else if (ret == 0) 
    { 
     // the socket has been closed 
    } 
    else { 
     // there is an error in the socket 
    } 
} 

如果您的問題被髮送該文件的長度,我不會亂用字符串和編碼,只需發送4個字節和讀取4個字節,這樣

byte[] bLength = new byte[4]; 
    int len = 123456; 
    bLength[0] = (byte)((len & 0xff000000) >> 24); 
    bLength[1] = (byte)((len & 0x00ff0000) >> 16); 
    bLength[2] = (byte)((len & 0x0000ff00) >> 8); 
    bLength[3] = (byte)(len & 0xff); 
    // Send 4 bytes 

    // Read only 4 bytes 
    byte[] buff = new byte[4]; 
    br.read(buff, 0, 4); 
    int length = (int)(buff[0] << 24) | (int)(buff[1] << 16) | (int)(buff[2] << 8) | buff[3]; 
+0

非常感謝你,它可能工作流didnt讀取整個圖像字節和missedmuch它的謝謝! –

相關問題