websocket - GO - Code stops executing after function return -
so, i'm trying construct websocket server in go. , ran interesting bug, cant life of me figure out why happening.
note: comments in code snippets there post. read them.
ive got function:
func join(ws *websocket.conn) { log.connection(ws) enc := json.newencoder(ws) dec := json.newdecoder(ws) var dj g.discussionjoin var disc g.discussion log.err(dec.decode(&dj), "dec.decode") ssd := g.finddiscussionbyid(dj.discussionid) ssdj := dj.convert(ws) g.dischandle <- &ssdj disc = ssd.convert() log.err(enc.encode(disc), "enc.encode") log.activity("discussion", "joined", disc.discussionid.subject) fmt.println("listening") //this gets called g.listen(dec) fmt.println("stoped listening") //this doesn't called [it should] ssdj.ssdiscussion.leave(ssdj.ssuserid) log.disconnection(ws) }
the function thats causing (in opinion) g.listen(...):
func listen(dec *json.decoder) { timelastsent := time.now().second() in := message{} ((timelastsent + conntimeout) % 60) != time.now().second() { if err := dec.decode(&in); err != nil { continue } else if in == ping { timelastsent = time.now().second() continue } timelastsent = time.now().second() messages <- in in = message{} } fmt.println("client timed out!") //this gets called return }
ive tried both , without return on last row of listen
as response @simoendre, ive left main method out of code example, since mentioned it, function takes g.messege{} out of messeges channel.
note: messagehandler() runs on own go routine.
func messagehandler() { msg := range messages { _, disc := range livingdiscussions { if disc.discussionid.udid == msg.udid { go disc.push(msg) break } } } }
looking @ listen
function remark has messages
channel receive the message{}
struct, in main goroutine not outputted. remember goroutines 2 way communication channels, means if channel receive input value must have output value channel not block.
so need create channel same struct type message{}
message := make(chan message{})
then in join function have pop out value pushed channel:
func join(ws *websocket.conn) { ... <-message }
update after new inputs:
it's not enough iterate on values coming channel, need inside go func()
.
getting values out of different concurrently executing goroutines can accomplished select
keyword, closely resembles switch control statement , called communications switch.
go func() { msg := range messages { _, disc := range livingdiscussions { if disc.discussionid.udid == msg.udid { select { case disc.push <- msg: // push channel value stack default : // default action } } } } }()
i don't know how disc.push
method implemented, if idea push received channel values stack have modify code in way send channel value array. in code snippet above i've wanted emphasize it's important values pushed channel.
Comments
Post a Comment