Interrupting a Go-routine Executing (*TCPListener) Accept
While creating a TCP server in Go, you may encounter the challenge of gracefully shutting down the server and interrupting the goroutine handling func (*TCPListener) Accept.
In Go, func (*TCPListener) Accept blocks execution until a connection is received. To interrupt this goroutine, you should:
Close the net.Listener:
The key to interrupting the Accept goroutine is to close the net.Listener obtained from net.Listen(...). By closing the listener, you signal the operating system that no more connections will be received, causing the Accept goroutine to exit.
Return from the Goroutine:
After closing the listener, ensure your goroutine returns. If the goroutine has code following the Accept call, it will continue executing and may cause unintended behavior or errors.
Example Code:
package main
import (
"fmt"
"net"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
if err != nil {
// Handle error
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
if err == net.ErrClosed {
return // Listener was closed
}
// Handle other errors
}
// Handle connection
conn.Close()
}
}()
fmt.Println("Press enter to stop...")
var input string
fmt.Scanln(&input)
ln.Close() // Close the listener, interrupting the Accept loop
}
This code creates a TCPListener on port 8080 and launches a goroutine that handles incoming connections in an infinite loop. When the user presses enter, the program closes the listener and interrupts the blocking Accept call, causing the goroutine to return.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3