There can be multiple reasons for getting such an error; a few of them are mentioned following:
- EC2 created in the wrong subnet group or private subnet
- Instance doesn't have a public IP or you are trying to connect with a private IP
- SSH/RDP port is not opened in the security group or the security group is not attached to the instance