duanran8648 2018-02-20 03:18
浏览 52
已采纳

如何捕获像ctrl + c这样的OS信号并通过Go中的Gorilla WebSocket发送它们

I am a newbie for go and websockets. I am trying to take input character by character and writing them to websocket. I even want to take ctrl+c as input and write it to websocket.

func (c *poc) writePump() {

    var err error

    exec.Command("stty", "-F", "/dev/tty", "cbreak", "min", "1").Run()
    exec.Command("stty", "-F", "/dev/tty", "-echo").Run()
    defer exec.Command("stty", "-F", "/dev/tty", "echo").Run()

    var b = make([]byte, 1)
    d := make(chan os.Signal, 1)
    signal.Notify(d, os.Interrupt)

    for {
        os.Stdin.Read(b)
        err = c.ws.WriteMessage(websocket.TextMessage, b)
        if err != nil {
            log.Printf("Failed to send UTF8 char: %s", err)
        }

        go func() {
            for sig := range d {
                // ????
            }
        }()
    }
}

This code is capturing the signal but not sure how to write to websocket.

  • 写回答

1条回答 默认 最新

  • douli2876 2018-02-20 04:13
    关注

    Send a CTRL-C with

    err = c.ws.WriteMessage(websocket.TextMessage, []byte{'\003'})
    if err != nil {
        // handle error
    }
    

    Other useful info:

    • The printf mentions UTF-8 characters, but there's no guarantee that the byte is a valid UTF-8 character. Consider using websocket.BinaryMessage instead.

    • Use a mutex to prevent concurrent writes to the websocket connection.

    • An alternative approach is to send the signal out of band to the peer and signal the remote process.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀