如何通过tcp流发送图像-c#winForms

如何通过tcp流发送图像-c#winForms,c#,winforms,tcp,C#,Winforms,Tcp,我正试图在我的C#Winforms聊天项目中通过TCP流发送图片。问题是,当它到达时,你只能看到一张空白照片 要发送图像,程序需要点击按钮1在服务器上,客户端检查服务器之前是否发送了“hii”。。。这有点傻,但请忽略 这是我的代码: 客户端: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; usin

我正试图在我的C#Winforms聊天项目中通过TCP流发送图片。问题是,当它到达时,你只能看到一张空白照片

  • 要发送图像,程序需要点击按钮1在服务器上,客户端检查服务器之前是否发送了“hii”。。。这有点傻,但请忽略
这是我的代码:

客户端:

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

namespace CLIENT
{
    public partial class client : Form
    {
        Socket sock;

        public client()
        {
            InitializeComponent();
            sock = socket();
            listBox1.DrawMode = DrawMode.OwnerDrawFixed;
            listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);

        }
        Socket socket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        }
        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            //
            // Draw the background of the ListBox control for each item.
            // Create a new Brush and initialize to a Black colored brush
            // by default.
            //
            e.DrawBackground();
            Brush myBrush = Brushes.Black;
            //
            // Determine the color of the brush to draw each item based on 
            // the index of the item to draw.
            //
            switch ((String)listBox1.Items[e.Index])
            {
                case "other:":
                    myBrush = Brushes.Green;
                    break;
                case "you:":
                    myBrush = Brushes.Red;
                    break;


            }
            //
            // Draw the current item text based on the current 
            // Font and the custom brush settings.
            //
            e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
                e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
            //
            // If the ListBox has focus, draw a focus rectangle 
            // around the selected item.
            //
            e.DrawFocusRectangle();


        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
        public Image byteArrayToImage(byte[] byteArrayIn)
        {

           // Bitmap bmp;
           // using (var ms = new MemoryStream(byteArrayIn))
            //{
              //  bmp = new Bitmap(ms);
            //}
            //return bmp;
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private void connectionButton_Click(object sender, EventArgs e)
        {
            try
            {
                sock.Connect(new IPEndPoint(IPAddress.Parse(textBox2.Text), 3));
                new Thread( () =>
                {
                    read();



                }).Start();
            }
            catch
            {
                MessageBox.Show("CONNECTION FAILED");
            }
        }
        void read()
        {

            while(true)
            {
                 try
                    {
                        byte[] buffer =new Byte[255];
                        int rec = sock.Receive(buffer,0, buffer.Length, 0);
                        if (rec <= 0)
                        {
                            throw new SocketException();
                        }
                        Array.Resize(ref buffer, rec);

                        Invoke((MethodInvoker)delegate
                             {
                                 if (listBox1.Items.Count > 1)
                                 {
                                    if (listBox1.Items[listBox1.Items.Count - 1].Equals("hii"))
                                       {

                                         Image i=byteArrayToImage(buffer);
                                           pictureBox1.Image =i ;

                                       }
                                  }
                                 listBox1.Items.Add("other:");
                                listBox1.Items.Add(Encoding.Default.GetString(buffer));
                             });

                    }
               catch
                {
                        MessageBox.Show("DISCONNECTION!");
                        Application.Exit();
                }
           }  
        }


        private void sendButton_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("you:");
            listBox1.Items.Add(textBox1.Text);
            byte[] data = Encoding.Default.GetBytes(textBox1.Text);
            sock.Send(data, 0, data.Length, 0);

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

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

namespace server
{
    public partial class server : Form
    {
        Socket sock;
        Socket acc;


        public server()
        {
            InitializeComponent();
            //this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            //this.ShowInTaskbar = false;
           listBox1.DrawMode = DrawMode.OwnerDrawFixed;
           listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);


        }
        Socket socket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        }
        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("you:");
            listBox1.Items.Add(textBox1.Text);
            byte[] data = Encoding.Default.GetBytes(textBox1.Text);
            acc.Send(data, 0, data.Length, 0);


        }
       private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
    //
    // Draw the background of the ListBox control for each item.
    // Create a new Brush and initialize to a Black colored brush
    // by default.
    //
    e.DrawBackground();
    Brush myBrush = Brushes.Black;
    //
    // Determine the color of the brush to draw each item based on 
    // the index of the item to draw.
    //
    switch ((String)listBox1.Items[e.Index])
    {
        case "other:":
            myBrush = Brushes.Green;
            break;
        case "you:":
            myBrush = Brushes.Red;
            break;


    }
    //
    // Draw the current item text based on the current 
    // Font and the custom brush settings.
    //
    e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), 
        e.Font, myBrush,e.Bounds,StringFormat.GenericDefault);
    //
    // If the ListBox has focus, draw a focus rectangle 
    // around the selected item.
    //
    e.DrawFocusRectangle();


    }
        private void listenButton_Click(object sender, EventArgs e)
        {
            sock = socket();

            sock.Bind(new IPEndPoint(0, 3));
            sock.Listen(0);

            new Thread(() =>
                {
                    acc = sock.Accept();
                    MessageBox.Show("CONNECTED ACCEPTED!");
                    sock.Close();
                    while(true)
                    {
                        try
                        {
                            byte[] buffer =new byte[255];
                            int rec =acc.Receive(buffer, 0, buffer.Length, 0);

                            if (rec<=0)
                            {
                                throw new SocketException();
                            }

                            Array.Resize(ref buffer, rec);
                            Invoke((MethodInvoker)delegate
                            {                             

                                listBox1.Items.Add("other:");




                                listBox1.Items.Add(Encoding.Default.GetString(buffer));

                            });
                        }
                        catch{
                                MessageBox.Show("DISCONNECTION!");
                                Application.Exit();
                        }
                    }
                }).Start();

        }

        private void server_Load(object sender, EventArgs e)
        {
            //this.Size = new Size(0, 0);
        }

        private void button1_Click(object sender, EventArgs e)
        {


           byte[] data = imageToByteArray(Image.FromFile("c:\\ss\\gg.png"));
            acc.Send(data, 0, data.Length, 0);
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
Net系统;
使用System.Net.Sockets;
使用系统线程;
使用系统文本;
使用System.IO;
命名空间客户端
{
公共部分类客户端:表单
{
插座;
公共客户机()
{
初始化组件();
sock=socket();
listBox1.DrawMode=DrawMode.OwnerDrawFixed;
listBox1.DrawItem+=新的DrawItemEventHandler(listBox1_DrawItem);
}
插座插座()
{
返回新套接字(AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp);
}
私有void listBox1_DrawItem(对象发送方,DrawItemEventArgs e)
{
//
//为每个项目绘制ListBox控件的背景。
//创建新笔刷并初始化为黑色笔刷
//默认情况下。
//
e、 牵引杆接地();
画笔我的画笔=画笔。黑色;
//
//确定要绘制每个项目的笔刷颜色
//要绘制的项的索引。
//
开关((字符串)listBox1.Items[e.Index])
{
案例“其他:”:
myBrush=画笔。绿色;
打破
案例“你:”:
myBrush=画笔。红色;
打破
}
//
//基于当前项目绘制当前项目文本
//字体和自定义笔刷设置。
//
e、 Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
e、 字体、myBrush、e.Bounds、StringFormat.GenericDefault);
//
//如果列表框有焦点,则绘制一个焦点矩形
//围绕选定的项目。
//
e、 DrawFocusRectangle();
}
私有void Form1\u加载(对象发送方、事件参数e)
{
}
公共字节[]imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms=新的MemoryStream();
保存(ms,System.Drawing.Imaging.ImageFormat.Png);
返回ToArray女士();
}
公共映像ByteArrayImage(字节[]byteArrayIn)
{
//位图bmp;
//使用(var ms=新内存流(byteArrayIn))
//{
//bmp=新位图(毫秒);
//}
//返回bmp;
MemoryStream ms=新的MemoryStream(byteArrayIn);
Image returnImage=Image.FromStream(毫秒);
返回图像;
}
私有无效连接按钮\单击(对象发送方,事件参数e)
{
尝试
{
Connect(新的IPEndPoint(IPAddress.Parse(textBox2.Text),3));
新线程(()=>
{
read();
}).Start();
}
抓住
{
MessageBox.Show(“连接失败”);
}
}
无效读取()
{
while(true)
{
尝试
{
字节[]缓冲区=新字节[255];
int rec=sock.Receive(buffer,0,buffer.Length,0);
如果(记录1)
{
if(listBox1.Items[listBox1.Items.Count-1].Equals(“hii”))
{
图像i=字节数组图像(缓冲区);
pictureBox1.Image=i;
}
}
列表框1.Items.Add(“其他:”);
listBox1.Items.Add(Encoding.Default.GetString(buffer));
});
}
抓住
{
MessageBox.Show(“断开连接!”);
Application.Exit();
}
}  
}
私有无效发送按钮\单击(对象发送程序,事件参数e)
{
listBox1.Items.Add(“您:”);
listBox1.Items.Add(textBox1.Text);
byte[]data=Encoding.Default.GetBytes(textBox1.Text);
发送(数据,0,数据长度,0);
}
私有无效列表框1\u SelectedIndexChanged(对象发送方,事件参数e)
{
}
}
}
服务器:

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

namespace CLIENT
{
    public partial class client : Form
    {
        Socket sock;

        public client()
        {
            InitializeComponent();
            sock = socket();
            listBox1.DrawMode = DrawMode.OwnerDrawFixed;
            listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);

        }
        Socket socket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        }
        private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            //
            // Draw the background of the ListBox control for each item.
            // Create a new Brush and initialize to a Black colored brush
            // by default.
            //
            e.DrawBackground();
            Brush myBrush = Brushes.Black;
            //
            // Determine the color of the brush to draw each item based on 
            // the index of the item to draw.
            //
            switch ((String)listBox1.Items[e.Index])
            {
                case "other:":
                    myBrush = Brushes.Green;
                    break;
                case "you:":
                    myBrush = Brushes.Red;
                    break;


            }
            //
            // Draw the current item text based on the current 
            // Font and the custom brush settings.
            //
            e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(),
                e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
            //
            // If the ListBox has focus, draw a focus rectangle 
            // around the selected item.
            //
            e.DrawFocusRectangle();


        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
        public Image byteArrayToImage(byte[] byteArrayIn)
        {

           // Bitmap bmp;
           // using (var ms = new MemoryStream(byteArrayIn))
            //{
              //  bmp = new Bitmap(ms);
            //}
            //return bmp;
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private void connectionButton_Click(object sender, EventArgs e)
        {
            try
            {
                sock.Connect(new IPEndPoint(IPAddress.Parse(textBox2.Text), 3));
                new Thread( () =>
                {
                    read();



                }).Start();
            }
            catch
            {
                MessageBox.Show("CONNECTION FAILED");
            }
        }
        void read()
        {

            while(true)
            {
                 try
                    {
                        byte[] buffer =new Byte[255];
                        int rec = sock.Receive(buffer,0, buffer.Length, 0);
                        if (rec <= 0)
                        {
                            throw new SocketException();
                        }
                        Array.Resize(ref buffer, rec);

                        Invoke((MethodInvoker)delegate
                             {
                                 if (listBox1.Items.Count > 1)
                                 {
                                    if (listBox1.Items[listBox1.Items.Count - 1].Equals("hii"))
                                       {

                                         Image i=byteArrayToImage(buffer);
                                           pictureBox1.Image =i ;

                                       }
                                  }
                                 listBox1.Items.Add("other:");
                                listBox1.Items.Add(Encoding.Default.GetString(buffer));
                             });

                    }
               catch
                {
                        MessageBox.Show("DISCONNECTION!");
                        Application.Exit();
                }
           }  
        }


        private void sendButton_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("you:");
            listBox1.Items.Add(textBox1.Text);
            byte[] data = Encoding.Default.GetBytes(textBox1.Text);
            sock.Send(data, 0, data.Length, 0);

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

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

namespace server
{
    public partial class server : Form
    {
        Socket sock;
        Socket acc;


        public server()
        {
            InitializeComponent();
            //this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            //this.ShowInTaskbar = false;
           listBox1.DrawMode = DrawMode.OwnerDrawFixed;
           listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem);


        }
        Socket socket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        }
        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            return ms.ToArray();
        }
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        private void sendButton_Click(object sender, EventArgs e)
        {
            listBox1.Items.Add("you:");
            listBox1.Items.Add(textBox1.Text);
            byte[] data = Encoding.Default.GetBytes(textBox1.Text);
            acc.Send(data, 0, data.Length, 0);


        }
       private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
    //
    // Draw the background of the ListBox control for each item.
    // Create a new Brush and initialize to a Black colored brush
    // by default.
    //
    e.DrawBackground();
    Brush myBrush = Brushes.Black;
    //
    // Determine the color of the brush to draw each item based on 
    // the index of the item to draw.
    //
    switch ((String)listBox1.Items[e.Index])
    {
        case "other:":
            myBrush = Brushes.Green;
            break;
        case "you:":
            myBrush = Brushes.Red;
            break;


    }
    //
    // Draw the current item text based on the current 
    // Font and the custom brush settings.
    //
    e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), 
        e.Font, myBrush,e.Bounds,StringFormat.GenericDefault);
    //
    // If the ListBox has focus, draw a focus rectangle 
    // around the selected item.
    //
    e.DrawFocusRectangle();


    }
        private void listenButton_Click(object sender, EventArgs e)
        {
            sock = socket();

            sock.Bind(new IPEndPoint(0, 3));
            sock.Listen(0);

            new Thread(() =>
                {
                    acc = sock.Accept();
                    MessageBox.Show("CONNECTED ACCEPTED!");
                    sock.Close();
                    while(true)
                    {
                        try
                        {
                            byte[] buffer =new byte[255];
                            int rec =acc.Receive(buffer, 0, buffer.Length, 0);

                            if (rec<=0)
                            {
                                throw new SocketException();
                            }

                            Array.Resize(ref buffer, rec);
                            Invoke((MethodInvoker)delegate
                            {                             

                                listBox1.Items.Add("other:");




                                listBox1.Items.Add(Encoding.Default.GetString(buffer));

                            });
                        }
                        catch{
                                MessageBox.Show("DISCONNECTION!");
                                Application.Exit();
                        }
                    }
                }).Start();

        }

        private void server_Load(object sender, EventArgs e)
        {
            //this.Size = new Size(0, 0);
        }

        private void button1_Click(object sender, EventArgs e)
        {


           byte[] data = imageToByteArray(Image.FromFile("c:\\ss\\gg.png"));
            acc.Send(data, 0, data.Length, 0);
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用系统组件模型;
使用系统数据;
使用系统图;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows.Forms;
Net系统;
使用System.Net.Sockets;
使用系统线程;
使用System.IO;
命名空间服务器
{
公共部分类服务器:表单
{
插座;
插座acc;
公共服务器()
{
初始化组件();
//this.FormBorderStyle=System.Windows.Forms.FormBorderStyle.None;
//this.ShowInTaskbar=false;
listBox1.DrawMode=DrawMode.OwnerDrawFixed;
listBox1.DrawItem+=新的DrawItemEventHandler(listBox1_DrawItem);
}
插座插座()
{
返回新套接字(AddressFamily.Int