How to capture os signals like ctrl+c and send them through gorilla websocket in go

。_饼干妹妹 提交于 2020-01-06 05:15:35

问题


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:


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.



来源:https://stackoverflow.com/questions/48877342/how-to-capture-os-signals-like-ctrlc-and-send-them-through-gorilla-websocket-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!