doucheng7534 2018-02-20 03:18
浏览 86
已采纳

如何捕获像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条回答 默认 最新

  • doulaozhang0238 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 用三极管设计一个单管共射放大电路
  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架