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.
To create a UNIX domain socket, use the socket function and specify AF_UNIX as the domain for the socket. The z/TPF system supports a maximum number of 16,383 active UNIX domain sockets at any time. After a UNIX domain socket is created, you must bind the socket to a unique file path by using the bind function.
Unix sockets use the same api as other types of sockets. They are created by socket sys call, and then you can connect to server socket by connect call, or bind it (if you need server socket). read/write calls can be used to perform IO.
The recv function is used to receive data over stream sockets or CONNECTED datagram sockets. If you want to receive data over UNCONNECTED datagram sockets you must use recvfrom().
Sockets allow communication between two different processes on the same or different machines. To be more precise, it's a way to talk to other computers using standard Unix file descriptors. In Unix, every I/O action is done by writing or reading a file descriptor.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With