日期:2014-05-18  浏览次数:20749 次

为什么我用socket把图象从客户端传递到服务器端的时候传输不全.
我在客户端截取了一段图片,为什么传输到服务器端的时候只传了一半,大部分都是黑色.

代码如下:


发送端:

  private void button1_Click(object sender, EventArgs e)
  {
   
  //建立终结点 
  System.IO.MemoryStream Stream = new System.IO.MemoryStream();
  pictureBox1.Image.Save(Stream, System.Drawing.Imaging.ImageFormat.Bmp);//存储为bmp图象
  byte[] b = Stream.ToArray();  
  //连接远程计算机 
  sendsocket.Send(b);
  //发送 

  Stream.Close();
  sendsocket.Shutdown(System.Net.Sockets.SocketShutdown.Send);
  //关闭发送连接 
  sendsocket.Close(); //关闭本 

  //***********************************************************************************************************end*******************************************************//

  }



接收端:
 private void button1_Click(object sender, EventArgs e)
  {
  this.label2.Text = "图象正在传输中,请稍侯";
  //设置接收数据缓冲区的大小
  byte[] b = new byte[300000000];
  System.Net.Sockets.Socket hostsocket = receivesocket.Accept();
  //如何确定该数组大小 
  System.IO.MemoryStream fs = new System.IO.MemoryStream();
  //接收数据
  hostsocket.Receive(b);
  fs.Write(b, 0, b.Length);
  Bitmap Img = new Bitmap(fs);
  pictureBox1.Image = Img;
  Img.Save("e:\\MyJpeg.jpg", ImageFormat.Jpeg);
  // this.Image1.ImageUrl = @"e:\MyJpeg.jpg";
  //关闭写文件流
  fs.Close();
  //关闭接收数据的Socket
  hostsocket.Shutdown(System.Net.Sockets.SocketShutdown.Receive);
  hostsocket.Close();
  this.label2.Text = "图象传输完毕";
  }



------解决方案--------------------
因为图片信息太大,你一次取不完,要循环取多次。
------解决方案--------------------
1代码没问题,先找个小一点的文件来发(不要多次接,只要刚开始那样)看看行不行
------解决方案--------------------
把你的接受缓存数组再加几个0试试