English 中文(简体)
发送和接收图像与c# /套接字
原标题:
  • 时间:2009-04-15 01:26:39
  •  标签:

我试图在c#设立了两个项目。基本上,一个简单的客户端服务器设置在我想要的服务器从客户端监听一个图像。然后在接收图像,将显示在一个图片框。

我一直跑到下面的错误:

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?

<强>听的服务器代码:< /强>

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)
        {

        }

    }
}

<强>客户端代码:< /强>

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;
        }
    }
}
问题回答

< /代码> <代码> ArgumentException告诉你流的图像格式是无效的。这可能是由客户端应用程序关闭内存流的数据被发送之前。

尝试更换<代码> byte [] bmpBytes = ms.GetBuffer(); < /代码>

byte[] bmpBytes = ms.ToArray();

或关闭数据流后发送。

记住,返回的字节数组<代码> .GetBuffer() < /代码>返回底层数组,不是一个副本(<代码> .ToArray() < /代码>返回一个副本),这是有效的,只要父流。

如果你有访问JPG文件本身(在这个例子中),你应该发送文件字节而不是使用图像/位图类。通过阅读一个JPG文件并重新编码成JPG你降低了图像的质量,导致不必要的开销。您可以使用<代码> File.ReadAllBytes() < /代码>快速获得完整的<代码> byte[] > < /代码或读/寄件如果你的内存空间是有限的。

一种更好的方式来发送图片是使用BinaryFormatter。

例如,一些片段来自我自己的代码来发送一个图像每一秒……

发送:

        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();
            }    
        } 

接收:

        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);
                }
            }
        }

和MessageData类简单地保存图像,可序列化的属性。

使用Arul年代代码来得到你想要的数据发送正确——.ToArray(),不是.GetBuffer ()。之后,你会想要在一个后台线程上运行服务器s startListening方法或者你不会看到任何形式(如线程运行服务器的代码会很忙。试一试:

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

在你Form_Load方法而不是直接调用startListening构造函数。

这是一个适合我的代码。用户启动服务器按钮,客户端打开文件对话框选择照片的电脑。最后发送图片,但小心照片大小因为UDP无法传送大量数据。

服务器:

    delegate void showMessageInThread(string message);
    UdpClient listener = null;
    IPEndPoint endpoint = null;
    Thread listenThread = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        startServer();
    }
    private void startServer()
    {
        endpoint = new IPEndPoint(IPAddress.Any, 1234);
        listener = new UdpClient(endpoint);
        ShowMsg("Waiting for a client!");

        listenThread = new Thread(new ThreadStart(Listening));
        listenThread.Start();
    }
    private void Listening()
    {
        while (true)
        {
            //take the coming data
            byte[] comingDataFromClient = listener.Receive(ref endpoint);
            ImageConverter convertData = new ImageConverter();
            Image image =  (Image)convertData.ConvertFrom(comingDataFromClient);
            pictureBox1.Image = image;
        }
   private void ShowMsg(string msg)
   {
      this.richTextBox1.Text += msg + "
";
   }

客户:

   Socket server = null;
    MemoryStream ms;
    IPEndPoint endpoint = null;
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        server = new Socket(AddressFamily.InterNetwork,
            SocketType.Dgram, ProtocolType.Udp);
        endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
    }
    private void btn_browse_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        string path = openFileDialog1.FileName;
        pictureBox1.Image = Image.FromFile(path);
        textPath.Text = path;
    }
    private void btn_send_Click(object sender, EventArgs e)
    {
        try
        {                
            ms = new MemoryStream();
            Bitmap bmp = new Bitmap(this.openFileDialog1.FileName);
            bmp.Save(ms, ImageFormat.Jpeg);
            byte[] byteArray = ms.ToArray();

            server.Connect(endpoint);
            server.SendTo(byteArray, endpoint);

            }
        }
        catch (Exception ex)
        {

        }
data = ReceiveVarData(client);
MemoryStream ms = new MemoryStream(data);
Image bmp = Image.FromStream(ms);
pictureBox1.Image = bmp;

The error may due to corrupted or incomplete bmp image received in the MemoryStream it worked fine for me after increasing the socket send/receive buffers values
adjust the sender "Socket.SendBufferSize" and the receiver "Socket.ReceiveBufferSize" to large values for example = 1024 * 2048 *10 this will help sending the entire image at once. or another solution is to check whether the received data size (data.length) is the same as the sent image data size, before the code line of forming the received image stream





相关问题
热门标签