Data not being sent over channels

Issue

I have this code here

https://gist.github.com/ChasingLogic/8324442

I’m trying to learn network programming with Golang this is my first attempt at concurrency and the goal is the equivalent of a stripped down irc server where a message is sent and echoed to all connected clients.

For some reason my code never gets past sending the data into the channels. If I put an error check in it just infinitely spits out EOF.

Solution

You have two problems:

  1. Empty buf in handleClient
  2. Deadlock between sender and receiver

The first is easy – just use “buf := make([]byte, 1024)” instead of “var buf []byte”.

The second one in more detail.

In handleClient you have

fmt.Println(string(buf[0:n]))
mesg <- buf[0:n]
fmt.Println(mesg)
ind <- n 
fmt.Println(ind)

So you send the message first and then – message length. But on receiver side you have:

n := <-ind
fmt.Println("N recieved")
buf := <-mesg
fmt.Println("Channels recieved")

So you expect message length before the message itself. So there is a deadlock: the sender is waiting for someone to receive the message before sending the length but receiver is waiting to receive message length before receiving the message.

Just change handleClient to have the opposite order and it will work:

fmt.Println(string(buf[0:n]))
ind <- n
mesg <- buf[0:n]
fmt.Println(mesg)
fmt.Println(ind)

Answered By – Kluyg

Answer Checked By – Willingham (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.