Transfer image over socket but cannot display it in picturebox C#
<p>I am writing code to transfer image over socket. In client side I have a button Send, and if in this button, I write code to connect to server, and then transfer image, it works OK. But now I create a button Connect, and I write code to connect to server in here (not in button Send), and in button Send I just transfer image, then I have some problems. Here is my client code:</p>

<pre><code>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 DevComponents.DotNetBar;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Drawing.Drawing2D;

namespace ImageSliderClient
{
    public partial class ImageSlider : Office2007RibbonForm
    {
        string splitter = "'\\'";
        string fName;
        string[] split = null;
        byte[] clientData;
        Socket client;

        public ImageSlider()
        {
            InitializeComponent();
            panelEx1.Controls.Add(pictureBox1);
        }

        private void resize(string path)
        {
            Bitmap bm = new Bitmap(path); //Create a bitmap from the original image
            Bitmap bm1 = new Bitmap(380, 268);
            Graphics g = Graphics.FromImage(bm1);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.DrawImage(bm, 0, 0, 380, 268);
            pictureBox1.Image = bm1;
            PictureBox pic = new PictureBox();
            pic.SizeMode = PictureBoxSizeMode.StretchImage;
            pic.Width = 65;
            pic.Height = 50;
            pic.Image = bm;
            flowLayoutPanel1.Controls.Add(pic);
            g.Dispose();
        }

        private void btSend_Click(object sender, EventArgs e)
        {
            if (tbPath.Text == "")
            {
                MessageBox.Show("Please choose an image!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (tbIP.Text == "")
            {
                MessageBox.Show("Please enter the server's IP!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

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

            try
            {
                byte[] fileName = Encoding.UTF8.GetBytes(fName); // filename
                byte[] fileData = File.ReadAllBytes(tbPath.Text); // data
                byte[] fileNameLen = BitConverter.GetBytes(fileName.Length); // the lenght of filename
                clientData = new byte[4 + fileName.Length + fileData.Length];

                fileNameLen.CopyTo(clientData, 0);
                fileName.CopyTo(clientData, 4);
                fileData.CopyTo(clientData, 4 + fileName.Length);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
                //client.Connect(IPAddress.Parse(tbIP.Text), 5000);
                lbStatus.Text = "Transfering...";
                client.Send(clientData);
                lbStatus.Text = "Transfered successfully!";
            }        
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            /*finally
            {
                client.Close();
            }*/

            try
            {
                resize(tbPath.Text); 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btSelect_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "JPEG(*.jpg)|*.jpg|Bitmap(*.bmp)|*.bmp|PNG(*.png)|*.png|GIF(*.gif)|*.gif|All files (*.*)|*.*";
            openFileDialog1.Title = "Choose an image!";
            openFileDialog1.FileName = "";
            char[] delimiter = splitter.ToCharArray();
            if (openFileDialog1.ShowDialog() == DialogResult.OK) tbPath.Text = openFileDialog1.FileName;    
            split = tbPath.Text.Split(delimiter);
            int limit = split.Length;
            fName = split[limit - 1].ToString();
            if (tbPath.Text != null) btSend.Enabled = true;
        }

        private void btConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                client.Connect(IPAddress.Parse(tbIP.Text), 5000);
                MessageBox.Show("Connect successfully!");
            }
            catch (SocketException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
</code></pre>

<p>And here is my server code:</p>

<pre><code>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 DevComponents.DotNetBar;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace ImageSliderServer
{
    public partial class ImageSlider : Office2007RibbonForm
    {
        #region Variable, Constructor, Property
        Thread t;
        Socket server;
        int flag = 0;
        string receivedPath;
        public delegate void UpdateStatusDelegate(string message);
        public delegate void ResizeDelegate_FlowLayoutPanel(PictureBox pb);
        public delegate void ResizeDelegate_PictureBox(Bitmap bm);

        public ImageSlider()
        {
            InitializeComponent();
            panelEx1.Controls.Add(pictureBox1);
            t = new Thread(new ThreadStart(StartListening));
            t.Start();
        }

        public class StateObject
        {
            // Client socket.
            public Socket workSocket = null;

            public const int BufferSize = 1024;
            // Receive buffer.
            public byte[] buffer = new byte[BufferSize];
        }
        #endregion

        #region Listen and accept an attempt of connection
        public static ManualResetEvent allDone = new ManualResetEvent(false);

        public void StartListening()
        {
            byte[] bytes = new Byte[1024];
            IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5000);
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //reuse the socket
                server.Bind(ipEnd);
                server.Listen(100);
                while (true)
                {
                    allDone.Reset();
                    server.BeginAccept(new AsyncCallback(AcceptConn), server);
                    allDone.WaitOne();
                }
            }
            catch (Exception ex)
            {
                UpdateStatus(ex.Message);
            }
        }

        public void AcceptConn(IAsyncResult iar)
        {
            allDone.Set();
            Socket listener = (Socket)iar.AsyncState;
            Socket handler = listener.EndAccept(iar);
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(Received), state);
            flag = 0;
        }
        #endregion

        #region Receive an image and display it in picturebox
        private void Received(IAsyncResult iar)
        {
            int fileNameLen = 1;
            String content = String.Empty;
            StateObject state = (StateObject)iar.AsyncState;
            Socket handler = state.workSocket;
            int bytesRead = handler.EndReceive(iar);
            if (bytesRead &gt; 0)
            {
                if (flag == 0)
                {
                    try
                    {
                        fileNameLen = BitConverter.ToInt32(state.buffer, 0);
                        string fileName = Encoding.UTF8.GetString(state.buffer, 4, fileNameLen);
                        receivedPath = "data/images/" + fileName;
                        UpdateStatus("Receiving an image...");
                        flag++;
                    }
                    catch (Exception ex)
                    {
                        //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                if (flag &gt;= 1)
                {
                    try
                    {
                        BinaryWriter writer = new BinaryWriter(File.Open(receivedPath, FileMode.Append));
                        if (flag == 1)
                        {
                            writer.Write(state.buffer, 4 + fileNameLen, bytesRead - (4 + fileNameLen));
                            flag++;
                        }
                        else writer.Write(state.buffer, 0, bytesRead);
                        writer.Close();
                    }
                    catch (IOException ex)
                    {
                        //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(Received), state);
                }
            }
            else
            {
                try
                {
                    resize(receivedPath);
                    UpdateStatus("Received successfully!");
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void resize(string path)
        {
            Bitmap bm = new Bitmap(path); //Create a bitmap from the original image
            Bitmap bm1 = new Bitmap(351, 280);
            Graphics g = Graphics.FromImage(bm1);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.DrawImage(bm, 0, 0, 351, 280);
            Resize_PictureBox(bm1);
            PictureBox pic = new PictureBox();
            pic.SizeMode = PictureBoxSizeMode.StretchImage;
            pic.Width = 65;
            pic.Height = 50;
            pic.Image = bm;
            pic.Cursor = Cursors.Hand;
            Resize_FlowLayoutPanel(pic);
            pic.Click += new EventHandler(pic_Click);
            g.Dispose();
        }

        private void pic_Click(object sender, EventArgs e)
        {
            PictureBox pic = (PictureBox)sender;
            pictureBox1.Image = pic.Image;
        }
        #endregion

        #region Handle cross-thread
        private void Resize_PictureBox(Bitmap bm)
        {
            if (pictureBox1.InvokeRequired)
            {
                pictureBox1.Invoke(new ResizeDelegate_PictureBox(Resize_PictureBox), new object[] { bm });
            }
            else
            {
                pictureBox1.Image = bm;
            }
        }

        private void Resize_FlowLayoutPanel(PictureBox pb)
        {
            if (flowLayoutPanel1.InvokeRequired)
            {
                flowLayoutPanel1.Invoke(new ResizeDelegate_FlowLayoutPanel(Resize_FlowLayoutPanel), new object[] { pb });
            }
            else
            {
                flowLayoutPanel1.Controls.Add(pb);
            }
        }

        private void UpdateStatus(string msg)
        {
            if (lbStatus.InvokeRequired)
            {

                lbStatus.Invoke(new UpdateStatusDelegate(UpdateStatus), new object[] { msg });
            }
            else
            {
                lbStatus.Text = msg;
            }
        }
        #endregion

    }  
}
</code></pre>

<p>In btSend_Click in client side, if I use code </p>

<pre><code>finally
            {
                client.Close();
            }
</code></pre>

<p>then I just transfer only one image, because the socket was closed, but If I don't use that code, then my client cannot display the image in picturebox. How can I solve my problem? Here is my source code: <a href="http://www.mediafire.com/?scc941be2coy7t6" rel="nofollow">http://www.mediafire.com/?scc941be2coy7t6</a></p>

<p>Thanks in advance :)</p>
