du7999 2017-01-21 08:55 采纳率: 100%
浏览 143
已采纳

使用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?

  • 写回答

1条回答 默认 最新

  • duancan65665 2017-01-21 12: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)                
      }                                               
    }                                     
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing
  • ¥15 手机/平板的浏览器里如何实现类似荧光笔的效果
  • ¥15 盘古气象大模型调用(python)
  • ¥15 传人记程序做的plc 485从机程序该如何写
  • ¥15 已知手指抓握过程中掌指关节、手指各关节和指尖每一帧的坐标,用贝塞尔曲线可以拟合手指抓握的运动轨迹吗?