/// <summary> /// Sends the start up information of the world to the client. /// </summary> private static void SendStartUp(NetworkController.SocketState state) { state.callBack = ProcessMessage; //Sends the world to the current socket NetworkController.NetworkHandler.Send(state, state.getID() + "\n" + world.width + "\n" + world.height + "\n"); Console.WriteLine("Sending startup info..."); }
private void FirstContact(NetworkController.SocketState state) { state.callMe = ReceiveStartup; this.Invoke(new MethodInvoker(() => this.nameBox.Enabled = true)); this.Invoke(new MethodInvoker(() => this.EnterName.Enabled = true)); stateToDealWithMyIssues = state; while (!EnterNameIsClicked) { } if (nameBox.Text == "") { MessageBox.Show("Please enter a name of more than one character or digit"); EnterNameIsClicked = false; FirstContact(state); } else { NetworkController.Network.Send(state, nameBox.Text + "\n"); } }
/*: it is important that the server sends the startup info before adding the client to the list of all clients. * This guarantees that the startup info is sent before any world info. Remember that the server is running a timer that may send world info to the list of clients at any time. */ /// <summary> /// /// </summary> /// <param name="state"></param> private static void ReceiveName(NetworkController.SocketState state) { // Socket getData = state.theSocket; state.callBack = (SendStartUp); Console.WriteLine(state.getID()); //This will only work for testing the FIRST client. We will have to change to something that determines the name among other possible messages..... string name = state.sb.ToString(); //create the new player and add him to the world. Snake player; //Locking this up to try and fix race cond lock (world) { player = world.AddNewSnake(name); } state.setID(player.getID()); SendStartUp(state); // Console.WriteLine(name); //Also locking to fix bug with two clients trying to connect. lock (connectedClients) { connectedClients.AddLast(state); } // Console.WriteLine(state.getID()); //Again, will have to change this to send player specific ID. NetworkController.NetworkHandler.AwaitDataFromServer(state); }
private void ReceiveStartup(NetworkController.SocketState state) { this.Invoke(new MethodInvoker(() => this.nameBox.Enabled = false)); this.Invoke(new MethodInvoker(() => this.EnterName.Enabled = false)); state.callMe = ReceiveWorld; stateToDealWithMyIssues = state; AbleToSendDirections = true; this.Invoke(new MethodInvoker(() => this.Focus())); int startupCase = 0; int worldStartWidth = 0; int worldStartHeight = 0; //Code to extract initial ourWorld data string totalData = state.sb.ToString(); string[] parts = Regex.Split(totalData, @"(?<=[\n])"); // Loop until we have processed all messages. // We may have received more than one. foreach (string p in parts) { // Ignore empty strings added by the regex splitter if (p.Length == 0) { continue; } // The regex splitter will include the last string even if it doesn't end with a '\n', // So we need to ignore it if this happens. if (p[p.Length - 1] != '\n') { break; } //only happens if we need to deal with \n switch (startupCase) { case 0: Snake ourSnake = new Snake(p); startupCase++; break; case 1: Int32.TryParse(p, out worldStartWidth); startupCase++; break; case 2: Int32.TryParse(p, out worldStartHeight); startupCase++; break; default: break; } //method invoker? state.sb.Remove(0, p.Length); } ourWorld = new World(worldStartWidth, worldStartHeight); this.Invoke((MethodInvoker) delegate { Size = new System.Drawing.Size(worldStartWidth * ourWorld.pixelsPerCell + 200, worldStartHeight * ourWorld.pixelsPerCell + 100); drawingPanel1.SetWorld(ourWorld); // Set the size of the drawing panel to match the ourWorld drawingPanel1.Width = ourWorld.width * ourWorld.pixelsPerCell; drawingPanel1.Height = ourWorld.height * ourWorld.pixelsPerCell; drawingPanel1.Invalidate(); }); state.callMe = ReceiveWorld; stateToDealWithMyIssues = state; NetworkController.Network.GetData(state); }
private void ReceiveWorld(NetworkController.SocketState state) { stateToDealWithMyIssues = state; //Parsing JSON stuff and updating ourWorld string totalData = state.sb.ToString(); string[] parts = Regex.Split(totalData, @"(?<=[\n])"); // Loop until we have processed all messages. // We may have received more than one. foreach (string p in parts) { // Ignore empty strings added by the regex splitter if (p.Length == 0) { continue; } // The regex splitter will include the last string even if it doesn't end with a '\n', // So we need to ignore it if this happens. if (p[p.Length - 1] != '\n') { break; } //deserialize //some random ip 128.110.21.208 //check to see if parts is a snake or food Json string // Parser the JSON string so we can examine it to determine what type of object it represents. JObject obj = JObject.Parse(p); JToken snakeProp = obj["vertices"]; JToken foodProp = obj["loc"]; JToken ID = obj["ID"]; if (snakeProp != null) { Snake s = JsonConvert.DeserializeObject <Snake>(p); namesAndScores[s.getName()] = s.snakeScore(s); if (!ourWorld.snakeDict.ContainsKey(s.getID())) { Label label = new Label(); this.Invoke((MethodInvoker) delegate { label.Name = "label" + labelNumber; label.Location = new System.Drawing.Point(ourWorld.width * ourWorld.pixelsPerCell + 20, 100 + labelNumber * 22); label.Size = new System.Drawing.Size(180, 20); label.Parent = this; label.ForeColor = s.getColor(); label.Text = s.getName() + ": " + s.snakeScore(s); s.myLabelNumber = labelNumber; labelNumber++; labelDict[label.Name] = label; this.Controls.Add(label); }); } else { this.Invoke(new MethodInvoker(() => labelDict["label" + s.myLabelNumber].ForeColor = s.getColor())); this.Invoke(new MethodInvoker(() => labelDict["label" + s.myLabelNumber].Text = s.getName() + ": " + s.snakeScore(s))); } lock (ourWorld.snakeDict) { ourWorld.snakeDict[s.getID()] = s; if (s.SnakeIsDead(s)) { ourWorld.snakeDict.Remove(s.getID()); this.Invoke(new MethodInvoker(() => labelDict["label" + s.myLabelNumber].Text = s.getName() + ": 0")); } } } if (foodProp != null) { Food f = JsonConvert.DeserializeObject <Food>(p); lock (ourWorld.foodDict) { ourWorld.foodDict[f.getID()] = f; if (f.FoodIsDead(f)) { ourWorld.foodDict.Remove(f.getID()); } } } state.sb.Remove(0, p.Length); } try { this.Invoke(new MethodInvoker(() => drawingPanel1.Invalidate())); } catch (Exception e) { //form should end now } NetworkController.Network.GetData(state); }
/// <summary> /// Used to read client input and react accordingly. /// </summary> private static void ProcessMessage(NetworkController.SocketState state) { //Save current ID to determine if we continue reading directions(If this ID snake is dead, do not read messages) int ID = state.getID(); //Saves the input to our message string message = state.sb.ToString(); //Used to seperate by newline string[] remove = { "\n" }; //Used to save direction from our string char direction; //Used to parse into int for passing direction to our world int temp; //Split each command to move string[] theMsg = message.Split(remove, StringSplitOptions.RemoveEmptyEntries); try { foreach (string dirC in theMsg) { //Assure is a valid and complete direction request if (dirC[0] == '(' && dirC[dirC.Length - 1] == ')') { direction = dirC[1]; lock (world) { // Console.WriteLine(direction); if (world.getAllSnakes().ContainsKey(ID)) { int.TryParse(direction.ToString(), out temp); // Console.WriteLine(temp); //Move the snake in the given direction. world.getAllSnakes()[ID].setDir(temp); // Console.WriteLine(world.getAllSnakes()[ID].getDir()); } else { } } } else if (dirC[0] == 'E' && dirC[1] == 'N' && dirC[2] == 'D') { state.sb.Clear(); state.callBack = null; Console.WriteLine("STATE ID:" + state.getID()); Console.WriteLine("CONNECTED CLIENT ID:" + connectedClients.First.Value.getID()); NetworkController.SocketState tempdel = null; foreach (NetworkController.SocketState el in connectedClients) { if (el.getID() == state.getID()) { tempdel = el; } } connectedClients.Remove(tempdel); Console.WriteLine("SIZE:" + connectedClients.Count); } //Remove processed message from buffer. state.sb.Remove(0, dirC.Length + 1); } if (state.getID() == -1) { } else { NetworkController.NetworkHandler.AwaitDataFromServer(state); } } catch (Exception) { } }
/// <summary> /// Handles when a new client connects by beginning recieve name /// </summary> /// <param name="state"></param> private static void HandleNewClient(NetworkController.SocketState state) { state.callBack = ReceiveName; NetworkController.NetworkHandler.AwaitDataFromServer(state); }