Socket发送和接受图片

以下是客户端(发送端)程序:

static void Main()
        {
            ShrinkPic sp = new ShrinkPic();
            sp.SmallPic("\test.jpg", 0.1f);
        }

        /// <param name="strOldPic">源图文件名(包括路径)</param>
        /// <param name="strNewPic">缩小后保存为文件名(包括路径)</param>
        /// <param name="intWidth">缩小至宽度</param>
        /// <param name="intHeight">缩小至高度</param>
        public class ShrinkPic

        //缩小图片的方法,昨天已经写过,不再注释
        {
            public void SmallPic(string strOldPic, float shrinkRatio)
            {
                Bitmap objPic, objNewPic;
                try
                {
                    objPic = new Bitmap(strOldPic);
                    objNewPic = new Bitmap((int)(objPic.Width * shrinkRatio), (int)(objPic.Height * shrinkRatio));
                    int intWidth = (int)(shrinkRatio * objPic.Width);
                    int intHeight = (int)(shrinkRatio * objPic.Height);
                    for (int i = 0; i < intWidth; i++)
                    {
                        for (int j = 0; j < intHeight; j++)
                        {
                            Color pixelColor = objPic.GetPixel(i * objPic.Width / intWidth, j * objPic.Height / intHeight);
                            objNewPic.SetPixel(i, j, pixelColor);
                        }
                    }

                    //pictureBox1.Image = objNewPic;客户端不用看到缩小后的图
                    MemoryStream imgStream = new MemoryStream();
                    objNewPic.Save(imgStream, ImageFormat.Jpeg);
                    byte[] imageb = imgStream.ToArray();

                    //以上三步把图片转为byte[],以便Socket发送
                    //objNewPic.Save("\new.jpg", ImageFormat.Jpeg);这是图片的Save方法
                    //objNewPic.Dispose();    还要用,不释放内存
                    //FileStream stream = File.OpenRead("\new.jpg");  用FileStream可读出指定位置文件

                    //以下是Socket通信(上面都是在缩小图片和转换格式)

                    try
                    {
                        IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.0.64"), 1080);

                        Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        sender.Connect(remoteEP);

                        sender.Send(imageb);  //Socket的Send方法只能发送byte[]型数据,因此把图片转为该格式

                        sender.Shutdown(SocketShutdown.Both);
                        sender.Close();

                    }

                    catch (Exception e)
                    {
                        MessageBox.Show(e.ToString());
                    }

                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.ToString());
                }

            }
        }

 

以下是服务器端(接收端)程序:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            SynchronousSocketListener.StartListening();

        }
    }
    public class SynchronousSocketListener
    {

        // Incoming data from the client.
        //public static string data = null;

        public static void StartListening()
        {

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 1080);

            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {

                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.

                while (true)
                {
                    //Console.WriteLine("Waiting for a connection…");
                    Socket handler = listener.Accept();
                    FileStream wrtr = new FileStream("\new.jpg", FileMode.Create);  //创建新文件"new.jpg"
                    byte[] buf = new byte[256]; 
                    handler.Receive(buf);    //接受数据读入缓冲区
                    NetworkStream nstrm = new NetworkStream(handler);   //用来读数据的数据流
                    nstrm.Flush();                //maopeng add here in case the buf space is too large
                    int dataRead = nstrm.Read(buf, 0, buf.Length);      //此次从buf读几个byte,存入dataRead

                    while (dataRead > 0)
                    {
                        wrtr.Write(buf, 0, dataRead);    //从buf读出dataRead个byte写入新文件
                        dataRead = nstrm.Read(buf, 0, buf.Length);  //数据读完时dataRead=0
                    }
                    nstrm.Close();
                    wrtr.Close();

                    MessageBox.Show("Picture received.");
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }

            catch (Exception e)
            {
                MessageBox.Show(e.ToString());

             }

        }

    }

调试时,客户端在Pocket PC模拟器上运行,服务器端在Windows Application中运行,可跟踪进度进行调试。

以上内容的参考资料主要是以前学习的HTTP Download方法和Socket通信两个程序。

另外由于HTTP与TCP通信读取数据的数据流不同,CSDN论坛中写到用NetworkStream类与Socket对象相关联为我提供了思路。关于NetworkStream的参考资料:http://topic.csdn.net/u/20080529/08/00d5c939-0b24-4cff-ba28-17cc23466305.html

把Bitmap转为byte[]的方法源自:http://www.itzhe.cn/article/20080125/62944.html

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s