doushi3454 2014-05-19 21:50
浏览 150
已采纳

如何使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.

  • 写回答

3条回答 默认 最新

  • douleijiang8111 2014-05-19 22:17
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog