The Internet of Things grew rapidly, and many services, applications, sensor-embedded electronic devices, and related protocols were created and are still being developed. The Internet of Things (IoT) allows physically existing things to see, hear, think, and perform a significant task by allowing them to interact with one another and exchange valuable knowledge when making decisions and caring out their vital tasks. The fifth-generation (5G) communications require that the Internet of Things (IoT) is aided greatly by wireless sensor networks, which serve as a permanent layer for it. A wireless sensor network comprises a collection of sensor nodes to monitor and transmit data to the destination known as the sink. The sink (or base station) is the endpoint of data transmission in every round. The major concerns of IoT-based WSNs are improving the network lifetime and energy efficiency. In the proposed system, Optimal Cluster-Based Routing (Optimal-CBR), the energy efficiency, and network lifetime are improved using a hierarchical routing approach for applications on the IoT in the 5G environment and beyond. The Optimal-CBR protocol uses the k-means algorithm for clustering the nodes and the multihop approach for chain routing. The clustering phase is invoked until two-thirds of the nodes are dead and then the chaining phase is invoked for the rest of the data transmission. The nodes are clustered using the basic k-means algorithm during the cluster phase and the highest energy of the node nearest to the centroid is selected as the cluster head (CH). The CH collects the packets from its members and forwards them to the base station (BS). During the chaining phase, since two-thirds of the nodes are dead and the residual energy is insufficient for clustering, the remaining nodes perform multihop routing to create chaining until the data are transmitted to the BS. This enriches the energy efficiency and the network lifespan, as found in both the theoretical and simulation analyses.