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 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败