V
V
v- death2015-10-31 22:02:42
go
v- death, 2015-10-31 22:02:42

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)
  }
}

Here, after each message, the connection is closed. I did not find an explanation on the Internet about how to close the connection not immediately, but after a certain period of time. (for example, this 20sec did not come, then we close the connection).
Decided
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.

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Gryaznov, 2015-11-05
@vGrabko99

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 question

Ask a Question

731 491 924 answers to any question