golang: tls.LoadX509KeyPair关闭net.Conn吗?

huangapple go评论83阅读模式
英文:

golang: tls.LoadX509KeyPair closes net.Conn?

问题

以下是翻译好的内容:

package main

import (
    "crypto/tls"
    "fmt"
    "log"
    "net"
)

func main() {
    ln, err := net.Listen("tcp", ":12345")
    if err != nil {
        log.Fatal(err)
    }

    for {
        c, err := ln.Accept()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(c)
        tls.LoadX509KeyPair("cert.pem", "key.pem") // 由 http://golang.org/src/pkg/crypto/tls/generate_cert.go 创建
    }
}
  1. 编译并运行此程序(go1.3.3 linux/amd64 @ubuntu14.04)。
  2. telnet localhost 12345
  3. telnet 命令立即退出。

tls.LoadX509KeyPair 方法会关闭 net.Conn 吗?

英文:
package main

import (
    "crypto/tls"
    "fmt"
    "log"
    "net"
)

func main() {
    ln, err := net.Listen("tcp", ":12345")
    if err != nil {
        log.Fatal(err)
    }

    for {
        c, err := ln.Accept()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(c)
        tls.LoadX509KeyPair("cert.pem", "key.pem") // created by http://golang.org/src/pkg/crypto/tls/generate_cert.go
    }
}
  1. compile and run this program(go1.3.3 linux/amd64 @ubuntu14.04)
  2. telnet localhost 12345
  3. telnet command exits immediatery

Is tls.LoadX509KeyPair closes net.Conn?

答案1

得分: 2

问题在于你在这里没有使用网络连接,而且它只是被垃圾回收清理掉了,因为循环的下一次迭代会重新声明 c

添加以下内容将在关闭连接之前在网络连接上显示一个 Hello 响应。

c.Write([]byte("HELLO\n"))
c.Close()
英文:

The problem is that you're not using the network connection for anything here, and it's simply getting cleaned up with garbage collection, since the next iteration through the loop is re-declaring c.

Adding the following will show you a Hello response on the network connection before closing it.

	c.Write([]byte("HELLO\n"))
	c.Close()

huangapple
  • 本文由 发表于 2014年10月2日 20:06:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/26160424.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定