2011-03-04 50 views
0

我是一個C#初學者面臨的問題有關從客戶端發送到服務器的圖像。我使用下面的代碼:ArgumentException當調用System.Drawing.Image.FromStream()

客戶:

try 
{ 
    Bitmap desktopBMP = CaptureScreen.CaptureDesktop(); 
    Image image = (Image)desktopBMP; 
    MemoryStream ms = new MemoryStream(); 
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); 

    if (m_clientSocket != null) 
    { 
     byte[] data = ms.ToArray(); 
     m_clientSocket.Send(data); 
    } 
} 
catch (Exception e) 
{ 
     sending = false; 
     MessageBox.Show(e.Message); 
} 

服務器:

// This the call back function which will be invoked when the socket 
// detects any client writing of data on the stream 

static int i = 0; 
public void OnDataReceived(IAsyncResult asyn) 
{ 
    SocketPacket socketData = (SocketPacket)asyn.AsyncState; 
    try 
    { 
      // Complete the BeginReceive() asynchronous call by EndReceive() method 
      // which will return the number of characters written to the stream 
      // by the client 
      int iRx = socketData.m_currentSocket.EndReceive(asyn); 
      byte[] data = new byte[iRx]; 
      data = socketData.dataBuffer; 
      MemoryStream ms = new MemoryStream(data); 
      Image image = Image.FromStream(ms); 
      image.Save(i + socketData.m_clientNumber+".jpg"); 
      i++; 

     // Continue the waiting for data on the Socket 
     WaitForData(socketData); 

    } 
    catch (Exception e) 
    { 
     MessageBox.Show(e.Message); 
    } 


// Start waiting for data from the client 
    public void WaitForData(SocketPacket socketPacket) 
    { 
     try 
     { 
     if (pfnWorkerCallBack == null) 
     { 
      // Specify the call back function which is to be 
      // invoked when there is any write activity by the 
      // connected client 
      pfnWorkerCallBack = new AsyncCallback(OnDataReceived); 
     } 

     socketPacket.m_currentSocket.BeginReceive(socketPacket.dataBuffer, 
                0, 
                socketPacket.dataBuffer.Length, 
                SocketFlags.None, 
                pfnWorkerCallBack, 
                socketPacket 
               ); 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.Message); 
     } 
    } 

客戶在每100毫秒發送圖像,這非常適用於一段時間,但有時「的ArgumentException」是在服務器中被調用的「System.Drawing.Image.FromStream()」函數拋出。

我在這裏做錯了什麼?我該如何改正它?

感謝

+0

在例外情況下的任何更多細節? – Blorgbeard 2011-03-04 00:39:19

+1

這看起來回答了我,你還需要什麼? – 2011-03-10 23:28:39

回答

1

望着MSDN page for Image.FromStream,它指出參數爲null或包含無效的圖像時拋出異常。你還可以將圖像數據散列發送到服務器,然後它可以用它來驗證您的圖像數據在傳輸過程中沒有被破壞?如果服務器損壞,服務器可以通知客戶端它應該重新發送圖像。我懷疑你正在運行這麼多的數據,以至於你偶爾會受到一些損壞。

還要添加一個臨時檢查,以確保在調試此問題時,您的socketData.dataBuffer沒有以某種方式設置爲null。

相關問題