我创建了一个全局通道,并且每当 ExampleNewWatcher 内部发生新事件时都会向它发送消息。第一次发生事件时,消息会在通道的接收端收到。但是,第二次发生事件时,我在通道的接收端没有收到消息。var messages = make(chan string)func ExampleNewWatcher(){ watcher, err := fsnotify.NewWatcher() if err != nil{ log.Fatal(err) } defer watcher.Close(0 done := make(chan bool) go func(){ for { select{ case event := <- watcher.Events: if event.Op&fsnotify.Write == fsnotify.Write{ log.Println("this logs twice if I create two write events") messages <- "this message only gets sent once even if I create two events" } case err := <- watcher.Errors: log.Println("error", err) } } }() err = watcher.Add("/tmp/watchedfile") <-done}func Websock(ws *websocket.Conn){ msg := <-messages log.Println("only one message arrives, even if I create for two events", msg) err := websocket.Message.Send(ws, msg)}func main(){ go ExampleNewWatcher() //for some reason, the server doesn't run unless I prefix a go routine to this watcher function, but that's another issue ... http.Handle("/websock", websocket.Handler(Websock)) log.Fatal(http.ListenAndServe(":8000", nil))}
2 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
将您的Websock功能修改为:
func Websock(ws *websocket.Conn) {
for {
msg := <-messages
log.Println("only one message arrives, even if I create for two events", msg)
if err := websocket.Message.Send(ws, msg); err != nil {
log.Fatal(err)
}
}
}
- 2 回答
- 0 关注
- 157 浏览
添加回答
举报
0/150
提交
取消