如何使Unix套接字监听器

问题描述:

this is really a more basic go idiom question but this serves as a good example. (BTW 100% go newb)

Trying to listen to unix socket and process messages. Stolen code from various places but I cant 'cast' things right

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)

    }
}

I need 'c' inside handleServerConnection to be of type UNixConn so that I can call ReadUNixMsg. But the generic Listen code makes a generic Conn object. So this code doesnt compile.

I tried various convert / cast type things UnixConn(c) for example but all to no avail.

这确实是一个更基本的go成语问题,但这是一个很好的例子。 (顺便说一句,百分百地换行了) p>

尝试监听unix套接字并处理消息。 来自各个地方的代码被盗,但是我无法正确地“投射”东西 p>

 包main 
 
import“ fmt” 
import“ net” 
 
func main(){\  n ln,err:= net.Listen(“ unix”,“ / var / service / daemon2”)
如果err!= nil {
 fmt.Println(err)
 return 
} 
 
  {
c,err:= ln.Accept()
如果err!= nil {
 fmt.Println(err)
继续
} 
 //处理连接
 go handleServerConnection(c)
  } 
 
 
} 
 
func handleServerConnection(c net.UnixConn){
 //收到消息
 buff:= make([] byte,1024)
 oob:= make([] byte  ,1024)
 
 _,_,_,_,err:= c.ReadMsgUnix(buff,oob); 
 if err!= nil {
 fmt.Println(err)
 
} 
  } 
  code>  pre> 
 
 

我需要在handleServerConnection中使用'c'作为UNixConn类型,以便我可以调用ReadUNixMsg。 但是,通用的Listen代码会生成通用的Conn对象。 因此,此代码不会编译。 p>

例如,我尝试了各种转换/强制转换类型的东西UnixConn(c),但都无济于事。 p> div>

Cast the connection like this:

 go handleServerConnection(c.(*net.UnixConn))

and change the function's signature to:

func handleServerConnection(c *net.UnixConn) {

What happens here is that net.Listen returns a Listener interface, which all listener sockets implement. The actual object is a pointer to net.UnixConn which implements the Listener interface. This allows you to do type assertion/conversion. This will fail of course if the object is not really a unix socket, so you'd better validate the assertion first.

Here's what you need to know about this stuff: http://golang.org/doc/effective_go.html#interface_conversions

Or you can use net.ListenUnix() which return a UnixListener on which you can call AcceptUnix which returns a *net.UnixConn.

But Not_a_Golfer solution works fine :)

What you are looking for is to replace your net.Listen with net.ListenUnixgram("unix", net.ResolveUnixAddr("unix","/path/to/socket") which will return the net.UnixConn object that you want.