我已经尝试解决这个问题很长一段时间了,这是一个相当烦人的问题。基本上,我有一个 XNA 程序,它连接到服务器并从中下载图片以用作纹理 2D。在 LAN 中测试时一切正常,但是当我将程序发送给朋友通过 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 上的上述问题?