none
有关TcpClient接收数据的问题 RRS feed

  • 问题

  • 想利用tcpclient写个发送图片接收图片的程序,可发送和接收都有点小问题
    发送的时候如果用FileStream获取已经存在的文件发送过去,有时候能获取到.而如果用Graphics截屏 直接转换byte[]却接受不到,,我比较过两种方法获取的byte[] 数据一模一样
    而且即便是利用FileStream发送已经存在的文件,接受的时候也有可能抛出"参数不正确"的异样
    就是在 Image.FromStream();这里出的异样.
    发送:
    Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Size.Width, Screen.PrimaryScreen.Bounds.Size.Height);
    Graphics g = Graphics.FromImage(bmp);
    g.CopyFromScreen(new Point(0, 0), new Point(0, 0), Screen.PrimaryScreen.Bounds.Size);
    
    string path = Path.Combine("e:\\", "test.jpg");
    bmp.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
    FileStream imgStream = new FileStream(path, FileMode.Open);
    
    //MemoryStream mstream = new MemoryStream();
    //bmp.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg);
    //byte[] bytes = mstream.ToArray();
    
    long length = imgStream.Length;
    byte[] bytes = new byte[length];
    imgStream.Read(bytes, 0, bytes.Length);
    imgStream.Close();
    TcpClient tc = new TcpClient();
    tc.Connect("127.0.0.1", 2111);
    NetworkStream netStream = tc.GetStream();
    netStream.Write(bytes, 0, bytes.Length);
    
    接收:
    TcpListener tl = new TcpListener(IPAddress.Any, 2111);
    tl.Start();
    while (true)
    {
      try
      {
        TcpClient tc = tl.AcceptTcpClient();
        NetworkStream netStream = tc.GetStream();
        byte[] bytes = new byte[10000];
        MemoryStream mStream = new MemoryStream();
        int length = 0;
        while (netStream.DataAvailable && (length = netStream.Read(bytes, 0, bytes.Length)) != 0)
        {
          mStream.Write(bytes, 0, length);
        }
    
        Image img = Image.FromStream(mStream);
    
        this.BeginInvoke(new ThreadStart(delegate()
        {
          this.pb.Image = img;
        }));
      }
      catch (Exception ex)
      {
        labMsg.Text = ex.Message.ToString();
      }
    }
    


    2011年8月17日 14:42

全部回复