func transmitter(id string, ws *websocket.Conn, c chan *registrar.T, ctx context.Context, cancel context.CancelFunc) { var err error var data *registrar.T defer ws.Close() //defer close(c) defer cancel() defer registrar.RemoveConnection(id) Loop: for { select { case data = <-c: err = websocket.JSON.Send(ws, *data) //websocket.Message.Send(ws, data.Msg) if err != nil { if !ws.IsClientConn() { log.Printf("transmitter closed\n") } else { log.Printf("transmitter error %v\n", err) } break Loop } case <-ctx.Done(): log.Printf("transmitter closed") break Loop } } }
func receiver(ws *websocket.Conn) { var ( ctx context.Context cancel context.CancelFunc ) ctx, cancel = context.WithCancel(context.Background()) c := make(chan *registrar.T) defer ws.Close() //defer close(c) defer cancel() ws.Request().ParseForm() id := ws.Request().FormValue("id") go transmitter(id, ws, c, ctx, cancel) err := registrar.NewConnection(id, c) if err != nil { fmt.Printf("New Connection Failed - Duplicate CLient Id %s\n", id) } else { for { var data *registrar.T = new(registrar.T) err := websocket.JSON.Receive(ws, data) if err != nil { log.Printf("echo handler error %v\n", err) break } data.From = id if data.Msg == "bye" { break } err = registrar.RouteMessage(data) if err != nil { log.Printf("Routing Error %v - %s\n", err, data.To) } } } registrar.RemoveConnection(id) }