通过TCP发送图像时出现损坏问题

时间:2013-01-19 12:51:43

标签: c# image tcp client-server corruption

我一直试图解决这个问题很长一段时间,这是一个相当烦人的问题。基本上,我有一个XNA程序连接到服务器并从中下载图片以用作texture2D。在局域网中测试时一切正常,但当我将程序发送给朋友通过WAN进行测试时,图像最终会随机损坏。在大多数情况下,图像的开始是在那里,但在那之后,它只是相同的颜色。我已经尝试了我能找到的所有解决方案,但似乎没有任何解决办法。这是我发送/接收图片的代码:

客户端

        NetworkStream nws = tcpcl.GetStream();
        while (true)
        {
            byte[] buffer = new byte[1024*1024*5];
            int buffpos = 0;
            while (nws.DataAvailable == false) Thread.Sleep(50);
            while (nws.DataAvailable == true)
            {
                buffer[buffpos] = (byte)nws.ReadByte();
                buffpos++;
            }

            byte[] actData = new byte[buffpos];
            for (int I = 0; I < buffpos; I++)
            {
                actData[I] = buffer[I];
            }

            string message = ASCIIEncoding.ASCII.GetString(actData);
            string ID = message.Substring(0, 1);
            string data = message.Substring(1);
            if (actData[0] == 1)
            {
                int namelength = BitConverter.ToInt32(actData, 1);
                byte[] _name= new byte[namelength];
                Array.Copy(actData, 5, _name, 0, namelength);
                string name = ASCIIEncoding.ASCII.GetString(_name);

                int avatarlength = BitConverter.ToInt32(actData, 5 + namelength);
                byte[] avatar = new byte[avatarlength];
                Array.Copy(actData, 9 + namelength, avatar, 0, avatarlength)
                    ;
                File.WriteAllBytes("content/" + name + ".png", avatar);

                FileStream fs=  File.OpenRead("Content/" + name + ".png");
                User _user = new User(name, Texture2D.FromStream(GraphicsDevice, fs));
                fs.Close();

                User.AddUser(_user);
            }
        }

服务器

                us.endpoint = new IPEndPoint(groupEP.Address, groupEP.Port);
                us.gameenabled = true;
                us.x = Game.spawnx;
                us.y = Game.spawny;

                byte[] player_avatar = Game.playerAvatar(us.Username);
                byte[] setup= new byte[5+player_avatar.Length];

                setup[0] = (byte)maxcls;
                BitConverter.GetBytes(player_avatar.Length).CopyTo(setup, 1);
                player_avatar.CopyTo(setup, 5);

                NetworkStream nws = us.clientsock.GetStream();
                nws.Write(setup, 0, setup.Length);

除了效率之外,代码中是否有任何可能导致WAN上出现问题的内容?

1 个答案:

答案 0 :(得分:0)

BrownishMonster在评论中解决了这个问题。

  

两个字节数组是否相同?我认为可能发生的是一些字节被错误地解释为控制字符。解决这个问题的方法是使用base64编码:Convert.ToBase64String或Convert.FromBase64String。