简体   繁体   中英

Networkstream not responding

I'm trying to send an image over a networkstream this is my client code:

   private void Form1_Load(object sender, EventArgs e)
    {

        TcpClient client=new TcpClient();
        client.Connect("127.0.0.1", 10);
       NetworkStream  ns = client.GetStream();
        Bitmap screen = GetDesktopImage();//generate a screenshot.
        MemoryStream ms = new MemoryStream();
        screen.Save(ms, ImageFormat.Png);

        byte[] byteCount = BitConverter.GetBytes((int)ms.Length);

        ms.Position = 0;
       ns.Write(byteCount, 0, byteCount.Length);
        ms.CopyTo(ns);
        ms.SetLength(0);



    }

this is the server:

    private void Start()
    {
        TcpListener listen = new TcpListener(IPAddress.Any, 10);
        listen.Start();

        NetworkStream ns = new NetworkStream(listen.AcceptTcpClient().Client);
        byte[] temp = new byte[4];
        ns.Read(temp, 0, 4);
        int count = BitConverter.ToInt32(temp, 0);   
        byte[] buff = new byte[count];
        pictureBox1.Image = Image.FromStream(ns);

    }


    private void Form1_Load(object sender, EventArgs e)
    {
        Thread th = new Thread(Start);
        th.Start();

    }

I dont see nothing on the picturebox and i guess the program hangs here- pictureBox1.Image = Image.FromStream(ns); just added a breakpoint there and it's not working. **Only when i close the client program and stop the debugging ,then i can see a image on the picturebox on the server side. Why is it?Any ideas?

My guess is that Image.FromStream does not know to stop reading when it has drawn the full image. Maybe the PNG format does not even allow for that. You need to give a stream to Image.FromStream that has a limited size. The easiest way would be to use BinaryReader.ReadBytes(count) to read the exact amount of bytes needed.

ns.Read(temp, 0, 4); : This is a bug because it assumes that the read will return exactly 4 bytes. This might not be the case. Again, use BinaryReader.ReadInt32 to safely read an int.

Better yet, abandon custom serialization formats and use something like protobuf length prefixed. Or, HTTP or WCF.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM