public bool CheckForHits(int clientNo, string data) { GridPosition pos = new GridPosition(int.Parse(data.Split(',')[0]), int.Parse(data.Split(',')[1])); Command cmd = new Command(); switch (clientNo) { case 0: if (client2Board.GetGridType(pos.x, pos.y) == GridType.Ship) { client2Board.ChangeGridType(pos.x, pos.y, GridType.Hit); client2Board.ShipSquaresRemaining--; return true; } else return false; case 1: if (client1Board.GetGridType(pos.x, pos.y) == GridType.Ship) { client1Board.ChangeGridType(pos.x, pos.y, GridType.Hit); client1Board.ShipSquaresRemaining--; return true; } else return false; } return false; }
private void SendCommandToClient(Command cmd) { if (clients[0].IP.Equals(cmd.TargetIP) && clients[0].Port.Equals(cmd.TargetPort)) { clients[0].SendCommand(cmd); } else if (clients[1].IP.Equals(cmd.TargetIP) && clients[1].Port.Equals(cmd.TargetPort)) { clients[1].SendCommand(cmd); } }
private void SendCommandToAll(Command cmd) { clients[0].SendCommand(cmd); clients[1].SendCommand(cmd); }
private bool SendCommandToTarget(Command cmd) { try { semaphor.WaitOne(); formatter.Serialize(networkStream, cmd); semaphor.Release(); return true; } catch { Console.WriteLine("Error Sending Data to client {0}:{1}", cmd.TargetIP, cmd.TargetPort); semaphor.Release(); return false; } }
public DisconnectEventArgs(Command cmd) { command = cmd; }
public void SendCommand(Command cmd) { if (socket != null && socket.Connected) { BackgroundWorker bgSender = new BackgroundWorker(); bgSender.DoWork += new DoWorkEventHandler(bgSender_Send); bgSender.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgSender_Completed); bgSender.WorkerSupportsCancellation = true; bgSender.RunWorkerAsync(cmd); } else { Console.WriteLine("Command failed to send to server"); } }
public void RequestClientList() { Command cmd = new Command(CommandType.ClientListRequest, ServerIP); cmd.TargetPort = ServerPort; cmd.SenderIP = IP; cmd.SenderName = Username; cmd.SenderPort = Port; SendCommand(cmd); }
private void SendUserStats(IPAddress targetIP, int targetPort, string data) { Command cmd = new Command(CommandType.UserDataInform, targetIP, data); cmd.TargetPort = targetPort; cmd.SenderIP = serverIP; cmd.SenderPort = serverPort; cmd.SenderName = "server"; SendCommandToClient(cmd); }
private bool RemoveClientFromList(IPAddress ip, int port) { lock (this) { int index = FindClientID(ip, port); if (index != -1) { string clientName = clientList[index].Username; clientList.RemoveAt(index); Command cmd = new Command(CommandType.UserDisconnected, IPAddress.Broadcast); cmd.SenderName = clientName; cmd.SenderIP = ip; cmd.SenderPort = port; SendCommandToAll(cmd); return true; } return false; } }
private void SendClientList(IPAddress targetIP, int targetPort) { string clientList = ""; string clientDetails = ""; foreach (ServerClient client in this.clientList) { clientDetails = client.IP.ToString() + ':' + client.Port.ToString() + ':' + client.Username + ':' + client.Wins.ToString() + ':' + client.Losses.ToString() + ','; clientList += clientDetails; } Console.WriteLine("Send Client list info to: " + targetIP + ':' + targetPort); Command cmd = new Command(CommandType.ClientListRequest, targetIP); cmd.TargetPort = targetPort; cmd.Data = clientList; cmd.SenderIP = serverIP; cmd.SenderPort = serverPort; cmd.SenderName = "Server"; SendCommandToClient(cmd); }
private void AnswerUsernameRequest(IPAddress targetIP, int targetPort, bool usernameAvailiability) { Command cmd = new Command(CommandType.UsernameRequest, targetIP, usernameAvailiability.ToString()); cmd.TargetPort = targetPort; cmd.SenderIP = serverIP; cmd.SenderPort = serverPort; cmd.SenderName = "Server"; Console.WriteLine("Username Response Sent to {0}:{1} Value: {2}", targetIP.ToString(), targetPort.ToString(), usernameAvailiability.ToString()); SendCommandToClient(cmd); }
private void DisconnectUser(Command dcCmd) { int index = FindClientID(dcCmd.SenderIP, dcCmd.SenderPort); string clientDetails = clientList[index].IP.ToString() + ":" + clientList[index].Port.ToString() + ":" + clientList[index].Username; Console.WriteLine("User {0}:{1} ({2}) has disconnected ({3}/{4})", dcCmd.SenderIP, dcCmd.SenderPort, clientList[index].Username, DateTime.Now.ToShortTimeString(), DateTime.Now.ToLongDateString()); clientList[index].Disconnect(); clientList.RemoveAt(index); Command cmd = new Command(CommandType.UserDisconnected, IPAddress.Broadcast); cmd.SenderName = dcCmd.SenderName; cmd.SenderIP = dcCmd.SenderIP; cmd.SenderPort = dcCmd.SenderPort; cmd.Data = clientDetails; SendCommandToAll(cmd); }
private void CommandRecieved(object sender, CommandEventArgs e) { //When a user connects set their client username if (e.Command.CommandType == CommandType.UserConnected) { string username = e.Command.Data.Split(':')[2]; Console.WriteLine("Checking for : " + username); bool nameAvailability = CheckUsernameAvailability(e.Command.SenderIP, e.Command.SenderPort, username); if (nameAvailability) { string data = CheckForClientData(username); SetClientUsername(e.Command.SenderIP, e.Command.SenderPort, username); SetClientData(e.Command.SenderIP, e.Command.SenderPort, data); SendUserStats(e.Command.SenderIP, e.Command.SenderPort, data); AnswerUsernameRequest(e.Command.SenderIP, e.Command.SenderPort, nameAvailability); e.Command.Data += (":" + data); SendCommandToAll(e.Command); } else if (nameAvailability == false) { AnswerUsernameRequest(e.Command.SenderIP, e.Command.SenderPort, nameAvailability); } } //User asks to disconnect if (e.Command.CommandType == CommandType.UserDisconnectRequest) { int index = FindClientID(e.Command.SenderIP, e.Command.SenderPort); string clientDetails = clientList[index].IP.ToString() + ":" + clientList[index].Port.ToString() + ":" + clientList[index].Username; Console.WriteLine("User {0}:{1} ({2}) has disconnected ({3}/{4})", e.Command.SenderIP, e.Command.SenderPort, clientList[index].Username, DateTime.Now.ToShortTimeString(), DateTime.Now.ToLongDateString()); clientList[index].Disconnect(); clientList.RemoveAt(index); Command cmd = new Command(CommandType.UserDisconnected, IPAddress.Broadcast); cmd.SenderName = e.Command.SenderName; cmd.SenderIP = e.Command.SenderIP; cmd.SenderPort = e.Command.SenderPort; cmd.Data = clientDetails; SendCommandToAll(cmd); } //Reply to client list request if (e.Command.CommandType == CommandType.ClientListRequest) { SendClientList(e.Command.SenderIP, e.Command.SenderPort); } //Sends message commands to all connected clients if (e.Command.CommandType == CommandType.Message) { if (e.Command.TargetIP.Equals(IPAddress.Broadcast)) { SendCommandToAll(e.Command); } else { SendCommandToClient(e.Command); } } //Pass challenge request to challenged user if (e.Command.CommandType == CommandType.ChallengeRequest) { int challengerID = FindClientID(e.Command.SenderIP, e.Command.SenderPort); e.Command.Data = clientList[challengerID].Wins + ":" + clientList[challengerID].Losses; SendCommandToClient(e.Command); } //Pass challenge response to challenger if (e.Command.CommandType == CommandType.ChallengeResponse) { SendCommandToClient(e.Command); } //Handle game start request if (e.Command.CommandType == CommandType.GameStartRequest) { IPAddress client2IP = IPAddress.Parse(e.Command.Data.Split(':')[0]); int client2Port = int.Parse(e.Command.Data.Split(':')[1]); int client1ID = FindClientID(e.Command.SenderIP, e.Command.SenderPort); int client2ID = FindClientID(client2IP, client2Port); BattleshipsGame game = new BattleshipsGame(clientList[client1ID], clientList[client2ID]); Command cmd = new Command(CommandType.GameIDInform, e.Command.SenderIP, activeGames.Count.ToString()); cmd.SenderName = "server"; cmd.SenderIP = serverIP; cmd.SenderPort = serverPort; cmd.TargetPort = e.Command.SenderPort; SendCommandToClient(cmd); cmd.TargetIP = client2IP; cmd.TargetPort = client2Port; SendCommandToClient(cmd); activeGames.Add(game); } //Handle ShipPlacementRequest if (e.Command.CommandType == CommandType.GameShipRequest) { activeGames[int.Parse(e.Command.Data.Split(':')[0])].CommandRecieved(e); } //Handle GameShotRequest if (e.Command.CommandType == CommandType.GameShotRequest) { activeGames[int.Parse(e.Command.Data.Split(':')[0])].CommandRecieved(e); } //Handle GameOverInform if (e.Command.CommandType == CommandType.GameOverInform) { activeGames[int.Parse(e.Command.Data.Split(':')[0])].GameOverMessageCount++; if (activeGames[int.Parse(e.Command.Data.Split(':')[0])].GameOverMessageCount >= 2) { PostGameStatisticsUpdate(activeGames[int.Parse(e.Command.Data.Split(':')[0])].Clients); activeGames.RemoveAt(int.Parse(e.Command.Data.Split(':')[0])); GC.Collect(); } } //Handle user data request if (e.Command.CommandType == CommandType.UserDataRequest) { int ID = FindClientID(e.Command.TargetIP, e.Command.TargetPort); string data = CheckForClientData(clientList[ID].Username); Command cmd = new Command(CommandType.UserDataInform, e.Command.SenderIP, data); cmd.SenderIP = e.Command.TargetIP; cmd.SenderPort = e.Command.TargetPort; cmd.SenderName = clientList[ID].Username; //Client username and IPEndpoint data is stored as command sender data cmd.TargetPort = e.Command.SenderPort; SendCommandToClient(cmd); } }
//Recieve and build a command to be processed private void Recieve(object sender, DoWorkEventArgs e) { while (socket.Connected) { try { Command cmd; cmd = (Command)formatter.Deserialize(networkStream); networkStream.Flush(); Console.WriteLine(cmd.CommandType + " Command Recieved"); cmd.SenderIP = IP; cmd.SenderPort = Port; if (cmd.CommandType == CommandType.UserConnected) cmd.SenderName = cmd.Data.Split(new char[] { ':' })[1]; else cmd.SenderName = clientUsername; OnCommandRecieved(new CommandEventArgs(cmd)); } catch (Exception sockEx) { Console.WriteLine("An error occurred involving client " + Username + " at: " + IP + ":" + Port + "." + Environment.NewLine + "Exception Message: " + sockEx.Message + Environment.NewLine + "Disconnecting client..."); Command dcCmd = new Command(CommandType.UserDisconnectRequest, IPAddress.Broadcast); dcCmd.SenderName = Username; dcCmd.SenderIP = IP; dcCmd.SenderPort = Port; OnDisconnected(new DisconnectEventArgs(dcCmd)); } } //this.OnDisconnected(new ClientEventArgs(this.socket)); }
public void CommandRecieved(CommandEventArgs e) { int clientNo = -1; if (clients[0].Username == e.Command.SenderName) { clientNo = 0; } else if (clients[1].Username == e.Command.SenderName) { clientNo = 1; } if (e.Command.CommandType == CommandType.GameShipRequest) { ParseShipData(e.Command.Data.Split(':')[1], clientNo); PlaceShips(clientNo); if (client1Board.setupComplete == true && client2Board.setupComplete == true) { Command cmd = new Command(CommandType.GameStartInform, e.Command.SenderIP); cmd.SenderName = "server"; cmd.TargetIP = clients[0].IP; cmd.TargetPort = clients[0].Port; cmd.Data = "true"; SendCommandToClient(cmd); Command cmd2 = new Command(CommandType.GameStartInform, clients[1].IP); cmd2.SenderName = "server"; cmd2.TargetPort = clients[1].Port; cmd2.Data = "false"; SendCommandToClient(cmd2); } } if (e.Command.CommandType == CommandType.GameShotRequest) { if (CheckForHits(clientNo, e.Command.Data.Split(':')[1])) { Command cmd = new Command(CommandType.GameShotResult, clients[clientNo].IP); cmd.Data = "hit"; cmd.TargetPort = clients[clientNo].Port; cmd.SenderName = "server"; SendCommandToClient(cmd); Command cmd2 = new Command(CommandType.GameHitInform, e.Command.TargetIP); cmd2.SenderName = "server"; cmd2.Data = e.Command.Data.Split(':')[1]; if (clientNo == 0) { cmd2.TargetIP = clients[1].IP; cmd2.TargetPort = clients[1].Port; } else if (clientNo == 1) { cmd2.TargetIP = clients[0].IP; cmd2.TargetPort = clients[0].Port; } SendCommandToClient(cmd2); //Check is any ships remain in each board, if a board has no ships remaining then the game is over and that client loses if (client1Board.AreShipsRemaining() == false) { Command winCmd = new Command(CommandType.GameOverInform, clients[1].IP, "win"); winCmd.TargetPort = clients[1].Port; clients[1].Wins++; SendCommandToClient(winCmd); Command lossCmd = new Command(CommandType.GameOverInform, clients[0].IP, "loss"); lossCmd.TargetPort = clients[0].Port; clients[0].Losses++; SendCommandToClient(lossCmd); } else if (client2Board.AreShipsRemaining() == false) { Command winCmd = new Command(CommandType.GameOverInform, clients[0].IP, "win"); winCmd.TargetPort = clients[0].Port; clients[0].Wins++; SendCommandToClient(winCmd); Command lossCmd = new Command(CommandType.GameOverInform, clients[1].IP, "loss"); lossCmd.TargetPort = clients[1].Port; clients[1].Losses++; SendCommandToClient(lossCmd); } } else { Command cmd = new Command(CommandType.GameShotResult, clients[clientNo].IP); cmd.Data = "miss"; cmd.TargetPort = clients[clientNo].Port; cmd.SenderName = "server"; SendCommandToClient(cmd); Command cmd2 = new Command(CommandType.GameMissInform, e.Command.TargetIP); cmd2.Data = e.Command.Data.Split(':')[1]; cmd2.SenderName = "server"; if (clientNo == 0) { cmd2.TargetIP = clients[1].IP; cmd2.TargetPort = clients[1].Port; } else if (clientNo == 1) { cmd2.TargetIP = clients[0].IP; cmd2.TargetPort = clients[0].Port; } SendCommandToClient(cmd2); } } }
private void SendCommandToAll(Command cmd) { IPEndPoint senderEndpoint = new IPEndPoint(cmd.SenderIP, cmd.SenderPort); foreach (ServerClient client in clientList) { if (client.Connected) { IPEndPoint endPoint = new IPEndPoint(client.IP, client.Port); if (endPoint != senderEndpoint) client.SendCommand(cmd); } } }
private void bgConnector_Connect(object sender, DoWorkEventArgs e) { try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(serverAddress); e.Result = true; networkStream = new NetworkStream(socket); bgReciever = new BackgroundWorker(); bgReciever.WorkerSupportsCancellation = true; bgReciever.DoWork += new DoWorkEventHandler(Recieve); bgReciever.RunWorkerAsync(); //Send connection command Command cmd = new Command(CommandType.UserConnected, IPAddress.Broadcast, IP.ToString() + ":" + Port.ToString() + ":" + Username); cmd.SenderIP = IP; cmd.SenderPort = Port; cmd.SenderName = Username; SendCommand(cmd); } catch { e.Result = false; } }
private void SendCommandToClient(Command cmd) { foreach (ServerClient client in clientList) { if (client.IP.Equals(cmd.TargetIP) && client.Port.Equals(cmd.TargetPort)) { client.SendCommand(cmd); break; } } }
private bool SendCommandToServer(Command cmd) { try { semaphor.WaitOne(); formatter.Serialize(networkStream, cmd); networkStream.Flush(); semaphor.Release(); return true; } catch { semaphor.Release(); Console.WriteLine("Error sending data to server"); return false; } }
public CommandEventArgs(Command cmd) { this.cmd = cmd; }
public void SignOut() { Command cmd = new Command(CommandType.UserDisconnectRequest, ServerIP); cmd.TargetPort = ServerPort; cmd.SenderIP = IP; cmd.SenderName = Username; cmd.SenderPort = Port; SendCommand(cmd); signingOut = true; }
public void SendCommand(Command cmd) { if (socket != null && socket.Connected) { BackgroundWorker bgSender = new BackgroundWorker(); bgSender.DoWork += new DoWorkEventHandler(bgSenderDoWork); bgSender.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgSenderCompleted); bgSender.RunWorkerAsync(cmd); } }