如何捕获像ctrl + c这样的os信号,并通过大猩猩websocket发送 [英] How to capture os signals like ctrl+c and send them through gorilla websocket in go
问题描述
我是一个新手,可以去websockets。我试图按字符输入字符并将它们写入websocket。我甚至想把ctrl + c作为输入并将其写入websocket。
func(c * poc)writePump(){
var err错误
exec.Command(stty,-F,/ dev / tty,cbreak,min,1)Run()
exec.Command(stty ,-F,/ dev / tty,-echo)。Run()
推迟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(发送失败的UTF8 char:%s,err)
}
去func(){
for sig:=范围d {
// ????
}()
}
}
此代码捕获信号,但不知道如何写入websocket。
发送CTRL-C err = c.ws.WriteMessage(websocket.TextMessage,[] byte {'\003'})
if err != nil {
//处理错误
}
其他有用的信息:
-
printf提到UTF-8字符,但不能保证该字节是有效的UTF-8字符。请考虑使用websocket.BinaryMessage。
-
使用互斥锁可防止并发写入websocket连接。 li>
另一种方法是将信号带外发送给对方并发信号给远程进程。
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.
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.
这篇关于如何捕获像ctrl + c这样的os信号,并通过大猩猩websocket发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!