How can I abort goroutine (* TCPListener) Accept?

I have been playing recently and am trying to make some kind of server that responds to clients on a tcp connection.

My question is how can I completely turn off the server and interrupt the current procedure, which is currently "locked" on the next call

func (* TCPListener) Accept?

According to Accept documentation

Accept implements the Accept method in the Listener interface; it waits for the next call and returns a generic Conn.

Errors are also very little documented.

+8
go
source share
3 answers

Here is what I was looking for. Maybe it helps someone in the future. Note the use of the select and c channel to combine it with the output channel

ln, err := net.Listen("tcp", ":8080") if err != nil { // handle error } defer ln.Close() for { type accepted struct { conn net.Conn err error } c := make(chan accepted, 1) go func() { conn, err := ln.Accept() c <- accepted{conn, err} }() select { case a := <-c: if a.err != nil { // handle error continue } go handleConnection(a.conn) case e := <-ev: // handle event return } } 
+2
source share

Just Close() net.Listener you get from net.Listen(...) and return from the running procedure.

+4
source share

TCPListener expiration date

You don't necessarily need the extra go procedure (which continues to take), just specify Deadline .

for example:

 for { // Check if someone wants to interrupt accepting select { case <- someoneWantsToEndMe: return // runs into "defer listener.Close()" default: // nothing to do } // Accept with Deadline listener.SetDeadline(time.Now().Add(1 * time.Second) conn, err := listener.Accept() if err != nil { // TODO: Could do some err checking (to be sure it is a timeout), but for brevity continue } go handleConnection(conn) } 
+2
source share

All Articles