du7999
2017-01-21 16:55
浏览 132
已采纳

使用Golang将JSON发送到Unix套接字

I'm trying to write a golang program to control mpv via issuing commands to a unix socket running at /tmp/mpvsocket.

This is what I've tried so far:

func main() {                                     
  c, err := net.Dial("unix", "/tmp/mpvsocket")    
  if err != nil {                                 
    panic(err)                                    
  }                                               
  defer c.Close()                                 

  _, err = c.Write([]byte(`{"command":["quit"]}`))
  if err != nil {                                 
    log.Fatal("write error:", err)                
  }                                               
}                                                 

This should cause mpv to quit but nothing happens.

This command can be issued via the command line to get the expected results:

echo '{ "command": ["quit"] }' | socat - /tmp/mpvsocket

It uses socat to send the JSON to the socket. How can I send this to the socket using Golang?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试编写golang程序,以通过向以下命令发送命令来控制 mpv Unix套接字运行在 / tmp / mpvsocket

这是我到目前为止已经尝试过的操作:

  func main(){
c,err:= net.Dial(“ unix”,“ / tmp / mpvsocket”)
 if err!= nil {
 panic(err)
} 
延迟c.Close  ()
 
 _,err = c.Write([] byte(`{“ command”:[“ quit”]}`)))
 if err!= nil {
 log.Fatal(“写入错误 :“,err)
} 
} 
   
 
 

这应该会导致mpv退出但什么也没发生。

这 可以通过命令行发出命令以获得预期结果:

  echo'{“ command”:[“ quit”]}''|  socat-/ tmp / mpvsocket 
   
 
 

它使用 socat 将JSON发送到套接字。 如何使用Golang将其发送到套接字?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duancan65665 2017-01-21 20:23
    已采纳

    Thanks to @AndySchweig in the comments above, I needed a new line after my JSON.

    The fixed line:

      _, err = c.Write([]byte(`{"command":["quit"]}` + "
    "))
    

    The full block of fixed code:

    func main() {                                     
      c, err := net.Dial("unix", "/tmp/mpvsocket")    
      if err != nil {                                 
        panic(err)                                    
      }                                               
      defer c.Close()                                 
    
      _, err = c.Write([]byte(`{"command":["quit"]}` + "
    "))
      if err != nil {                                 
        log.Fatal("write error:", err)                
      }                                               
    }                                     
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题