7

golang 中listener close之后,积压在内核的连接就没法accept了

 2 years ago
source link: https://phpor.net/blog/post/17547
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

golang 中listener close之后,积压在内核的连接就没法accept了 – PHPor 的Blog

 

测试实例:

package main
import (
"bufio"
"fmt"
"net"
"sync"
func main() {
addr := "127.0.0.1:8181"
ln, err := net.Listen("tcp", addr)
if err != nil {
panic(err)
return
conn1, err := net.Dial("tcp", addr)
if err != nil {
panic(err)
n, err := fmt.Fprintf(conn1, "client hello\n")
if err != nil {
panic(err)
if n == 0 {
panic("应该能发送成功的")
wg := &sync.WaitGroup{}
wg.Add(1)
go func(conn net.Conn) {
defer wg.Done()
r := bufio.NewReader(conn)
l, _ , _ := r.ReadLine()
println("s:", string(l))
conn.Close()
}(conn1)
//ln.Close() // 如果这里 Close的话,下面的Accept就会失败,尽管上面有一个已经创建成功的连接
conn, err := ln.Accept()
if err != nil {
panic(err)
clientHello, _, _  := bufio.NewReader(conn).ReadLine()
fmt.Println("c:", string(clientHello))
fmt.Fprintf(conn, "server hello\n")
conn.Close()
wg.Wait()

 Posted by phpor at 下午 6:07

 Leave a Reply Cancel reply

Your Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Name (required)

E-mail (required)

URI

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK