发送和接收图像通过套接字用C# [英] Sending and receiving an image over sockets with C#

查看:132
本文介绍了发送和接收图像通过套接字用C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图建立在C#中的两个程序。基本上,一个简单的客户端服务器架设在那里我希望服务器监听来自客户端的图像。然后,在接收到的图像,将在一个图片中显示它。

我一直运行到以下错误:


  

类型的第一次机会异常
  System.ArgumentException发生在
  System.Drawing.dll程序


该错误是发生在服务器code,它是在该行听:
图片BMP = Image.FromStream(毫秒);
有任何想法吗?

服务器code监听:

 使用系统;
使用System.Collections.Generic;
使用System.ComponentModel;
使用System.Data这;
使用System.Drawing中;
使用System.Linq的;
使用System.Text;
使用System.Windows.Forms的;
使用System.IO;
使用System.Net;
使用的System.Net.Sockets;命名空间的NetView
{
    公共部分Form1类:表格
    {
        公共Form1中()
        {
            的InitializeComponent();
            startListening();
        }        私人无效startListening()
        {
            ////////////////////////////////////////////            Console.WriteLine(服务器开始......);
            字节[]数据=新的字节[1024];
            IPEndPoint IPEP =新IPEndPoint(IPAddress.Any,9050);            插座newsock =新的Socket(AddressFamily.InterNetwork,
                            SocketType.Stream,ProtocolType.Tcp);            newsock.Bind(IPEP);
            newsock.Listen(10);
            Console.WriteLine(等待客户端...);            客户端的Socket = newsock.Accept();
            IPEndPoint newclient =(IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine(在港跟{0} {1},
                            newclient.Address,newclient.Port);            而(真)
            {
                数据= ReceiveVarData(客户端);
                MemoryStream的毫秒=新的MemoryStream(数据);
                尝试
                {
                    图片BMP = Image.FromStream(毫秒);
                    pictureBox1.Image = BMP;
                }
                赶上(ArgumentException的E)
                {
                    Console.WriteLine(破事);
                }
                如果(data.Length == 0)
                    newsock.Listen(10);
            }
            从{0},newclient.Address //Console.WriteLine(\"Disconnected);
            client.Close();
            newsock.Close();
            /////////////////////////////////////////////        }        私人静态的byte [] ReceiveVarData(插座S)
        {
            INT总= 0;
            INT recv的;
            字节[]数据大小=新的字节[4];            的recv = s.Receive(数据大小,0,4,0);
            INT大小= BitConverter.ToInt32(数据大小,0);
            INT dataleft =大小;
            字节[]数据=新的字节[大小]
            而(共<大小)
            {
                的recv = s.Receive(数据,总计dataleft,0);
                如果(recv的== 0)
                {
                    打破;
                }
                总+ = recv的;
                dataleft - = recv的;
            }
            返回的数据;
        }        私人无效Form1_Load的(对象发件人,EventArgs的发送)
        {        }    }
}

客户端code:

 使用系统;
使用System.Net;
使用的System.Net.Sockets;
使用System.Text;
使用System.Drawing中;
使用System.IO;命名空间ConsoleApplication2
{
    类节目
    {
        静态无效的主要(字串[] args)
        {
            字节[]数据=新的字节[1024];
            INT发送;
            IPEndPoint IPEP =新IPEndPoint(IPAddress.Parse(127.0.0.1),9050);            套接字服务器=新的Socket(AddressFamily.InterNetwork,
                            SocketType.Stream,ProtocolType.Tcp);            尝试
            {
                server.Connect(IPEP);
            }
            赶上(SocketException E)
            {
                Console.WriteLine(无法连接到服务器。);
                Console.WriteLine(e.ToString());
                到Console.ReadLine();
            }
            BMP位图=新位图(C:\\\\ eek256.jpg);            MemoryStream的毫秒=新的MemoryStream();
            //保存到内存中采用JPEG格式
            bmp.Save(MS,System.Drawing.Imaging.ImageFormat.Jpeg);            //读取结束
            字节[] = bmpBytes ms.GetBuffer();
            bmp.Dispose();
            ms.Close();            发送= SendVarData(服务器,bmpBytes);            Console.WriteLine(从服务器断开连接...);
            server.Shutdown(SocketShutdown.Both);
            server.Close();
            到Console.ReadLine();
        }        私有静态诠释SendVarData(插座S,字节[]数据)
        {
            INT总= 0;
            INT大小= data.Length;
            INT dataleft =大小;
            INT发送;            字节[]数据大小=新的字节[4];
            数据大小= BitConverter.GetBytes(大小);
            发送= s.Send(数据大小);            而(共<大小)
            {
                发送= s.Send(数据,总共dataleft,SocketFlags.None);
                总+ =发送;
                dataleft - =发送;
            }
            总回报;
        }
    }
}


解决方案

的ArgumentException 告诉你流中的图像格式是无效的。这可能是由客户端应用程序关闭存储流引起被发送的数据之前。

尝试更换字节[] = bmpBytes ms.GetBuffer();

 字节[] = bmpBytes ms.ToArray();

或者关闭流中的数据被送到了。

请记住,通过返回的字节数组的 .GetBuffer()返回底层数组,而不是它(副本 .ToArray() 返回副本),只要是有效的父流。

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

解决方案

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.

这篇关于发送和接收图像通过套接字用C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆