Please see the code below:
package main import "net" import "log" import "bufio" import "time" func main() { l,_:=net.Listen("tcp", ":8888") for { conn, _ := l.Accept() log.Println("get conn", conn.RemoteAddr()) go func() { f, _:=conn.(*net.TCPConn).File() d:=f.Fd() log.Println(d) f.Close() arr := make([]byte, 1000) reader := bufio.NewReader(conn) time.AfterFunc(3*time.Second, func() { log.Println("close conn", conn.RemoteAddr()) conn.Close() }) for { size, err := reader.Read(arr) if err != nil { break } log.Println("sss", arr[:size]) } }() } }
when the program start,I use telnet to connect the localhost:8888,after 3 seconds,the server will kill me out, but the socket status is still ESTABLISHED when I use netstat to watch.If I remove the File() function, the socket can be closed normally.How can I fix this?
if err != nil {log.Fatal(err)}
. You make everyone looking at your code wonder if there is some error fromListen
orAccept
(orClose
) orFile()
that is just being ignored. – Dave Cdefer f.Close()
just on the next line after you open the file? – Pie 'Oh' Pah