一个频道只能收到一条消息

我创建了一个全局通道,并且每当 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))


}



慕丝7291255
浏览 158回答 2
2回答

LEATH

您的 WebSock 函数需要包含一个接收循环来接收多个消息。否则,您的函数将终止并且 websocket 连接将被关闭。

慕姐8265434

将您的Websock功能修改为:func Websock(ws *websocket.Conn) {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; msg := <-messages&nbsp; &nbsp; &nbsp; &nbsp; log.Println("only one message arrives, even if I create for two events", msg)&nbsp; &nbsp; &nbsp; &nbsp; if err := websocket.Message.Send(ws, msg); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go