How to Gracefully Shut Down a Go TCP Server and Interrupt the `(*TCPListener) Accept` Goroutine?

Patricia Arquette
Release: 2024-11-03 07:27:02
Original
755 people have browsed it

How to Gracefully Shut Down a Go TCP Server and Interrupt the `(*TCPListener) Accept` Goroutine?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template