I'm building an echo algorithm in go with multiple initiators, essentially I have three functions "talk", "listen" and "run algorithm". "talk" sends data to neighbours, "listen" received data from neighbours, both of these use channels. These channels are monitored within the "run algorithm" functions which decides what to send and to whom.
Essentially this:
func server(s Node, myChannel chan string){
fmt.Printf("SERVER Launching server... %s:%s
", s.ip, s.port)
// Start listening
// We do not stop listening until the surrounding function returns (finishes)
ln, _ := net.Listen("tcp", s.ip+":"+s.port)
for {
// Accept connections
fmt.Println("SERVER waiting at ln.Accept()")
conn, err := ln.Accept()
if err != nil {
panic(err)
}
//fmt.Println("SERVER connection accepted")
// Read received message
fmt.Println("SERVER awaiting message")
message, err := bufio.NewReader(conn).ReadString('
')
fmt.Println("SERVER message received = " + message)
if err != nil {
fmt.Println("the server is broken")
panic(err)
}
if err == nil {
// If the mmessage is not empty, then print it in the shell
if string(message) != "" {
fmt.Println("SERVER message put in channel")
myChannel <- message
}
}
}
And the talking function as this:
func client(myNode Node, nbour Node, myChannel chan string) {
for {
// this loop controls the sending of algorithm messages
conn, err = net.Dial("tcp", nbour.ip+":"+nbour.port)
// useful info for the user
//fmt.Println("CLIENT awaiting message to send")
// the the message to send out of the channel
messageToSend := <-myChannel
// send the message
conn.Write([]byte(messageToSend))
fmt.Println("CLIENT SENT ALG MESSAGE = " + messageToSend + "to " + nbour.ip + ":" + nbour.port)
// useful information for the user
//fmt.Printf("CLIENT Message text: " + messageToSend. + "
")
}
The problem is that these connections work find for the first few messages, then at some arbitrary point one node sends a message and the neighbour does not receive it and everything stops.
Thus my question is why do connections arbitrarily stop, is there a setting somewhere to tell them how long to stay open, or how many messages to send? Or is the above code the wrong was of achieving this goal (although like I say it works fine sometimes, in fact sometimes the algorithm completes perfectly, then I run exactly the same code again and it gets stuck waiting for messages to arrive).