Answer the question
In order to leave comments, you need to log in
How to wait for new data and not close the connection?
Hello. I understand writing tcp daemons. Here, with the help of docks, I made a simple code
package main
import (
"fmt"
"log"
"net"
)
func main() {
l, err := net.Listen("tcp", ":2000")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
go func(c net.Conn) {
buf := make([]byte, 1024)
c.Read(buf)
fmt.Print(string(buf))
c.Close()
}(conn)
}
}
buf := make([]byte, 1024) for { c.Read(buf) fmt.Print(string(buf)) }
I can remove connection closing. But I can not understand, but how to constantly wait for new messages? And then after the first SMS, the following do not get into the terminal.
Answer the question
In order to leave comments, you need to log in
Are you sure you're checking everything correctly? Of course, the way to not close the connection is not very correct, but it should work. An almost 1v1 example from the net.Listener documentation should work.
As for the timeout, the connection (net.Conn) can be set with the "SetReadDeadline(t time.Time) error" method. For other cases, there is a universal sync package
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question