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:
<code class="go">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 }</code>
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.
The above is the detailed content of How to Gracefully Shut Down a Go TCP Server and Interrupt the `(*TCPListener) Accept` Goroutine?. For more information, please follow other related articles on the PHP Chinese website!