/// <summary> /// Processes the message received from the server. If it is a json object, it updates the world accordingly. /// Otherwise, it is either the player id or world size, and thus sets those accordingly. /// </summary> private void ProcessMessage(SocketState state) { if (state.ErrorOccured) { return; } //Gets data and parts from data string totalData = state.GetData(); string[] parts = Regex.Split(totalData, @"(?<=[\n])"); foreach (string s in parts) { //If the part has a length of 0, then it is not a complete message if (s.Length <= 0) { continue; } //If the part does not end with newline, then the message is incomplete if (s[s.Length - 1] != '\n') { break; } //If the part is a json, deserialize if (s[0] == '{') { lock (world) { //Get the json object out of the part JObject obj = JObject.Parse(s); JToken type; //Wall is not loaded if (!world.WallsLoaded) { type = obj["wall"]; if (type != null) { Wall w = JsonConvert.DeserializeObject <Wall>(s); world.AddWall(w.ID, w.p1, w.p2); } else { //As soon as we reach a JSON that isn't a wall, the walls are loaded world.LoadWalls(); WorldLoaded(); } } //If it a tank, update the world type = obj["tank"]; if (type != null) { Tank t = JsonConvert.DeserializeObject <Tank>(s); world.UpdateTank(t.ID, t.location, t.orientation, t.aiming, t.name, t.hitPoints, t.score, t.died, t.disconnected); } //Projectile type = obj["proj"]; if (type != null) { Projectile p = JsonConvert.DeserializeObject <Projectile>(s); world.UpdateProjectile(p.ID, p.location, p.orientation, p.owner, p.died); } //Powerup type = obj["power"]; if (type != null) { Powerup p = JsonConvert.DeserializeObject <Powerup>(s); world.UpdatePowerup(p.ID, p.location, p.died); } //Beam type = obj["beam"]; if (type != null) { Beam b = JsonConvert.DeserializeObject <Beam>(s); BeamFired(b); } } } //If it is not a json object, then it must be the world size or player id else { //If player id is not set, then the part is the player id if (PlayerID < 0) { PlayerID = Int32.Parse(s); IDLoaded(); } //Otherwise, the part must be the world else { world = new World(Int32.Parse(s)); } } lock (state) { //Remove the processed part state.RemoveData(0, s.Length); } //If OnUpdate is set, call it if (OnUpdate != null) { OnUpdate(); } } }