tags:

views:

4157

answers:

6

I am trying to set up two programs in C#. Basically, a simple client server set up where I want the server to listen for an image from the client. Then, upon receiving the image, will display it in a PictureBox.

I keep running into the following error:

A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dll

The error is happening on the server code that is listening at this line: Image bmp = Image.FromStream(ms); Any ideas?

The Server code that listens:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace NetView
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            startListening();
        }

        private void startListening()
        {
            ////////////////////////////////////////////

            Console.WriteLine("Server is starting...");
            byte[] data = new byte[1024];
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

            Socket newsock = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream, ProtocolType.Tcp);

            newsock.Bind(ipep);
            newsock.Listen(10);
            Console.WriteLine("Waiting for a client...");

            Socket client = newsock.Accept();
            IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Connected with {0} at port {1}",
                            newclient.Address, newclient.Port);

            while (true)
            {
                data = ReceiveVarData(client);
                MemoryStream ms = new MemoryStream(data);
                try
                {
                    Image bmp = Image.FromStream(ms);
                    pictureBox1.Image = bmp;
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine("something broke");
                }


                if (data.Length == 0)
                    newsock.Listen(10);
            }
            //Console.WriteLine("Disconnected from {0}", newclient.Address);
            client.Close();
            newsock.Close();
            /////////////////////////////////////////////

        }

        private static byte[] ReceiveVarData(Socket s)
        {
            int total = 0;
            int recv;
            byte[] datasize = new byte[4];

            recv = s.Receive(datasize, 0, 4, 0);
            int size = BitConverter.ToInt32(datasize, 0);
            int dataleft = size;
            byte[] data = new byte[size];


            while (total < size)
            {
                recv = s.Receive(data, total, dataleft, 0);
                if (recv == 0)
                {
                    break;
                }
                total += recv;
                dataleft -= recv;
            }
            return data;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

    }
}

The Client Code:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Drawing;
using System.IO;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            int sent;
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);

            Socket server = new Socket(AddressFamily.InterNetwork,
                            SocketType.Stream, ProtocolType.Tcp);

            try
            {
                server.Connect(ipep);
            }
            catch (SocketException e)
            {
                Console.WriteLine("Unable to connect to server.");
                Console.WriteLine(e.ToString());
                Console.ReadLine();
            }


            Bitmap bmp = new Bitmap("c:\\eek256.jpg");

            MemoryStream ms = new MemoryStream();
            // Save to memory using the Jpeg format
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            // read to end
            byte[] bmpBytes = ms.GetBuffer();
            bmp.Dispose();
            ms.Close();

            sent = SendVarData(server, bmpBytes);

            Console.WriteLine("Disconnecting from server...");
            server.Shutdown(SocketShutdown.Both);
            server.Close();
            Console.ReadLine();
        }

        private static int SendVarData(Socket s, byte[] data)
        {
            int total = 0;
            int size = data.Length;
            int dataleft = size;
            int sent;

            byte[] datasize = new byte[4];
            datasize = BitConverter.GetBytes(size);
            sent = s.Send(datasize);

            while (total < size)
            {
                sent = s.Send(data, total, dataleft, SocketFlags.None);
                total += sent;
                dataleft -= sent;
            }
            return total;
        }
    }
}
+2  A: 

ArgumentException tells you that the image format in the stream is invalid. Which is probably caused by the client application closing the memory stream before the data were sent.

Try replacing byte[] bmpBytes = ms.GetBuffer(); with

byte[] bmpBytes = ms.ToArray();

Or close the stream after the data were sent.

Remember that the byte-array returned by the .GetBuffer() returns the underlying array, not a copy of it (.ToArray() returns a copy), that is valid as long as the parent stream.

arul
+2  A: 

Use Arul's code to get the data to send correctly -- you want .ToArray(), not .GetBuffer(). Then, you'll want to run the server's 'startListening' method on a background thread or you won't actually see anything (as the form thread will be busy running the server code. Try:

var t = new Thread(startListening);
t.IsBackground = true;
t.start();

In your Form_Load method instead of directly calling startListening in your constructor.

Jonathan
A: 

The threading code works great. I changed my code to ms.ToArray(), but I'm still getting the error..

A first chance exception of type 'System.ArgumentException' occurred in System.Drawing.dll m1.cs:line 49 System.ArgumentException: Parameter is not valid. at System.Drawing.Image.FromStream(Stream stream, Boolean useEmbeddedColorManagement, Boolean validateImageData) at System.Drawing.Image.FromStream(Stream stream) at NetView.Form1.startListening()

Ronald
Use the comment feature on the post you are replying to.
Spencer Ruport
use the debugger to check the contents of the array you are sending, and the one you are receiving to make sure they match.
Lamar
I didn't have high enough reputation to comment on my post. :P I think it is because I registered after I posted this question and my authorship didn't carry over. Anyways, still trying to solve this problem...
Ronald
A: 

Do I need to do something with JPEG compression on the server side to open the stream?

Ronald
no, it can determine the file encoding (JPG) automatically.
Lucas
+1  A: 

If you have access to the JPG file itself (as in the example), you should send the file bytes and not use the Image/Bitmap classes. By reading a JPG file and re-encoding into JPG you are decreasing the image quality and incurring unnecessary overhead. You can use File.ReadAllBytes() to quickly get the complete byte[] or read/send it in pieces if your memory space is limited.

Lucas
+1  A: 

A better way to send the image would be to use BinaryFormatter.

eg, some snippets from my own code to send an image every second...

sending:

        TcpClient client = new TcpClient();  
        try  
        {    
            client.Connect(address, port); 

            // Retrieve the network stream.  
            NetworkStream stream = client.GetStream();  
            MessageData data = new MessageData(imageToSend); 

            IFormatter formatter = new BinaryFormatter();

            while(true)
            {
                formatter.Serialize(stream, data);
                Thread.Sleep(1000);
                data.GetNewImage();
            }    
        }

receiving:

        TcpListener listener = new TcpListener(address, port);
        listener.Start();

        try
        { 
            using (TcpClient client = listener.AcceptTcpClient())
            {
                stream = client.GetStream();

                IFormatter formatter = new BinaryFormatter();
                while (true)
                {
                    MessageData data = (MessageData)formatter.Deserialize(stream);

                    if (ImageReceivedEvent != null) ImageReceivedEvent(data.Picture);
                }
            }
        }

and the MessageData class simply holds the image and has the [Serializable] attribute.

geometrikal