我正在尝试运行原始游戏服务器。到目前为止,我到了这一点(注释行)并且服务器运行顺利。但是如果我再次从客户端发送对象,它不会更新超过一次。例如,客户端发送具有新位置 Vector2(400,50) 的序列化播放器对象,但服务器将其反序列化到具有旧位置的对象。
播放器代码
namespace Commons.Game
{
[Serializable]
public class Unit
{
#region Fields
public int ID;
public Vector2 position;
public string name;
public int HP;
public int XP;
public int Lvl;
public bool active;
public float speed;
public string password;
#endregion
public Unit(Vector2 position, int HP, float speed, string name, string password, int ID)
{
active = true;
this.position = position;
this.HP = HP;
this.XP = 0;
this.speed = speed;
this.name = name;
this.Lvl = 1;
this.password = password;
this.ID = ID;
}
服务器代码
namespace SocketServer.Connection
{
class Server
{
#region Fields
Unit[] players;
UdpClient playersData;
Thread INHandlePlayers;
BinaryFormatter bf;
IPEndPoint playersEP;
#endregion
public Server()
{
this.players = new Unit[5];
bf = new BinaryFormatter();
this.playersData = new UdpClient(new IPEndPoint(IPAddress.Any, 3001));
this.playersEP = new IPEndPoint(IPAddress.Any, 3001);
this.INHandlePlayers = new Thread(new ThreadStart(HandleIncomePlayers));
this.INHandlePlayers.Name = "Handle income players.";
this.INHandlePlayers.Start();
}
private void HandleIncomePlayers()
{
Console.Out.WriteLine("Players income handler started.");
MemoryStream ms = new MemoryStream();
while (true)
{
byte[] data = playersData.Receive(ref playersEP);
ms.Write(data, 0, data.Length);
ms.Position = 0;
Unit player = null;
player = bf.Deserialize(ms) as Unit; //<-- 1st deserialization is OK, bu after another client update, object doesn't change. So I change Vector with position at client, that sends correct position I want, but at server side position doesn't change after first deserialization.
Console.Out.WriteLine(player.name + " " + player.position.X + " " + player.position.Y);
ms.Flush();
for (int i = 0; i < players.Length; i++)
{
if (players[i] != null && player.ID == players[i].ID)
{
players[i] = player;
break;
}
}
}
}
}