matryer/goblueprints

[Chapter 1][Second Edition] Questions about infinite for loop and chat

Closed this issue · 2 comments

  1. I modify "read" function in "client.go" file. likes below
    but, i couldn't check infinite "client read" message in my terminal
    i don't understand about that.
func (c *client) read() {
	defer c.socket.Close()
	for {
		c.tracer.Trace("client read")
		_, msg, err := c.socket.ReadMessage()
		if err != nil {
			return
		}
		c.room.forward <- msg
	}
}
  1. client template sent the message using "socket.send()" function.
    but, i don't understand after "socket.send()" situation.
    the message will arrive "room.go"? then, why the message sent room.go?
    i don't understand .. please help me

i found a answer for first question.
c.socket.ReadMessage() wait for messages
so, print "client read" message in terminal once every chat

also, write() in client.go.
for msg := c.send {}
equals below code.

for {
  if msg, ok := <- c.send; ok {
    
  }
}

so, write() in client.go has infinite loop.

and i found a answer for second question.

  1. socket.send() will send message to "client instance" made by ServeHTTP in room.go
  2. run "client instance" 's read function then the message will send c.room.forward
  3. room's run() catch the channel message of r.forward and, send the message to every client's c.send
  4. run "client instance" 's write function then the message will send client browser
  5. Appear the message in client's browser

i think, this order