我有一个主机名到连接的映射,我试图将它传递给我在 Go 中编写的应用程序的不同模块。
var conns_ map[string]net.Conn // tcp connections per node
在主 server.go 文件中,我拨打网络中的其他服务器并将连接保存到此地图:
conn, err := net.Dial("tcp", address)
conns_[hostname] = conn
然后我想将此映射发送到其他模块以重新使用连接。这是我如何将其发送到学习者模块的示例:
go learner.ListenForNotifies(conns_, selfname_)
在学习器模块中,我获取地图并开始尝试在它包含的每个连接上使用 gob.Decoder:
func ListenForNotifies(conns map[string]net.Conn, selfname string) {
for hostname, conn := range conns {
go listen(hostname, conn, lChan)
}
// etc.
}
在监听函数中:
func listen(hostname string, conn net.Conn, lChan chan string) {
decoder := gob.NewDecoder(conn)
proposal := &utils.Proposal{}
err := decoder.Decode(proposal)
// etc.
}
问题是,当我在这里调用decoder.Decode(proposal) 时,会发生恐慌:
panic: runtime error: invalid memory address or nil pointer dereference
我在其他地方使用相同的编码/解码代码没有问题,唯一的区别是我试图重用连接而不是在同一函数中建立新连接后立即调用 decode。我一直试图使这项工作几个小时,试图通过引用传递事物,使用 map[string]interface{},以及各种没有运气的东西。Gob.decode 应该阻塞,直到在底层 net.Conn 对象上编码了一些东西,对吧?我只能猜测 net.Conn 对象此时已经以某种方式失效了。
我在传递连接对象的方式上有什么问题吗?我读到 net.Conn 是一个非常简单的对象,可以通过值传递,但我一定遗漏了一些东西。当尝试使用 type interface{} 通过引用传递它时,我收到如下错误:
interface {} does not implement net.Conn (missing Close method)
我现在不知所措,试图找出连接对象可能有什么问题,如果我误用了 gob.Decode,那么将 net.Conn 对象放入地图就会出现问题,或者问题是否完全不同.
有任何想法吗?
ABOUTYOU
相关分类