这真是一个更基本的成语问题,但这是一个很好的例子.(BTW 100%go newb)
尝试监听unix套接字并处理消息.从各个地方偷来的代码,但我不能'把'正确的东西
package main
import "fmt"
import "net"
func main(){
ln,err := net.Listen("unix", "/var/service/daemon2")
if err!= nil {
fmt.Println(err)
return
}
for {
c, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
}
// handle the connection
go handleServerConnection(c)
}
}
func handleServerConnection(c net.UnixConn) {
// receive the message
buff := make([]byte, 1024)
oob := make([]byte, 1024)
_,_,_,_,err:=c.ReadMsgUnix(buff,oob);
if err != nil {
fmt.Println(err)
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在handleServerConnection中使用'c'为UNixConn类型,以便我可以调用ReadUNixMsg.但是通用的Listen代码构成了一个通用的Conn对象.所以这段代码没有编译.
我尝试了各种转换/转换类型的东西UnixConn(c),但都无济于事.
像这样建立连接:
go handleServerConnection(c.(*net.UnixConn))
Run Code Online (Sandbox Code Playgroud)
并将函数的签名更改为:
func handleServerConnection(c *net.UnixConn) {
Run Code Online (Sandbox Code Playgroud)
这里发生的是net.Listen返回Listener所有侦听器套接字实现的接口.实际对象是net.UnixConn实现Listener接口的指针.这允许您进行类型断言/转换.如果对象实际上不是unix套接字,那么这当然会失败,所以你最好先验证断言.
以下是您需要了解的内容:http://golang.org/doc/effective_go.html#interface_conversions
| 归档时间: |
|
| 查看次数: |
1156 次 |
| 最近记录: |