A sinkhole attack is characterized by low difficulty to launch, high destructive power, and difficulty to detect and defend. It is a common attack mode for wireless sensor networks. This paper proposes a sinkhole attack detection and defense strategy integrating SPA and Jaya algorithms in wireless sensor networks (WSNs). Then, combined with the SPA trust model, the trust values of suspicious nodes were calculated, and the attack nodes were detected. The Jaya algorithm was adopted to avoid the attacked area so that nodes can find the route to communicate with the real Sink, and attack nodes are isolated in the network to improve the capabilities of network directional defense. The simulation results show that the improved detection algorithm can effectively detect malicious nodes in the network, and the defense strategy implemented in the attacked area can improve the packet delivery rate, reduce network delay and energy consumption, and improve the security and reliability of wireless sensor networks.