public void ReceiveMsg( TcpClient tmpTcpClient ) { try { if ( tmpTcpClient.Connected ) { NetworkStream ns = tmpTcpClient.GetStream( ); byte[] receiveBytes = new byte[tmpTcpClient.ReceiveBufferSize]; FileStream fs = new FileStream( "D:\\aa.png" , FileMode.Create ); bool isfirst = true; int i = 0; while ( ns.Read( receiveBytes , 0 , receiveBytes.Length ) > 0 ) { if ( isfirst ) { fs.Write( receiveBytes , 4 , receiveBytes.Length - 4 ); isfirst = false; } else { fs.Write( receiveBytes , 0 , receiveBytes.Length ); } } if ( fs != null ) { fs.Dispose( ); } } } catch ( Exception ex ) { MessageBox.Show( "出问题了" ); } }
求大神帮我看看 我这是用来接返回的二进制图片流的,有时候保存的图片是能看到的,但是也只是一半,有时候保存的图片直接看不到,而且while循环玩了之后 下面的程序也不走下面的if.不知道是什么情况 卡了几天了求大神
ns.Read( receiveBytes , 0 , receiveBytes.Length )
这句代码读取的字节数不一定等于receiveBytes.Length的,所以不能用fs.Write( receiveBytes , 0 , receiveBytes.Length )把receiveBytes的内容全部写入到文件,而是应该看ns.Read( receiveBytes , 0 , receiveBytes.Length )的返回值count,写入count个字节到文件
即ns.Read( receiveBytes , 0 , receiveBytes.Length )变为var count = ns.Read( receiveBytes , 0 , receiveBytes.Length )
fs.Write( receiveBytes , 0 , receiveBytes.Length )变为fs.Write( receiveBytes , 0 , count )
当然还需要注意如果count小于4,就得进行判断了
建议1:read到的具体长度是要看read的返回值的
建议2:请在传输png图片流之前的ok\r\n中增加指示图片流数据总长度的数据,之后需要边收边判断图片长度到了没,到了就是收完了。当然,png图片格式本身也有数据头,里面也带了图片长度的。不过那个解析起来麻烦些