Reputation: 4400
I'm a C# beginner facing problems regarding sending an image from a client to a server. I use the following code :
Client :
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);
}
Server :
// 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);
}
}
The client sends images at every 100 ms and this works well for a while but sometimes a "ArgumentException" is thrown by the called "System.Drawing.Image.FromStream()" function in the server.
What am I doing something wrong here ? and how should I correct it ?
Thanks
Upvotes: 0
Views: 1866
Reputation: 1204
Looking at the MSDN page for Image.FromStream, it states that the parameter is either null or contains an invalid image when that exception is thrown. Can you also send a hash of the image data to the server, which it could then use to validate your image data hasn't been corrupted in transit? If it is corrupt the server could notify the client that it should resend the image. I suspect that you are running so much data that the odds are you are receiving an occasional corrupt bit.
Also add a temporary check just to make sure your socketData.dataBuffer hasn't somehow been set to null while you are debugging this issue.
Upvotes: 1