V
V
vlarkanov2019-10-02 14:40:54
go
vlarkanov, 2019-10-02 14:40:54

How to gracefully end reading bufio.Scaner()?

There is a client and a server. The client sends JSON like this:

writer := bufio.NewWriter(conn)
JSONmessage = []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)
writer.Write(JSONmessage)

And the server reads like this:
for {
    scanned := scanr.Scan()
    if !scanned {
      if err := scanr.Err(); err != nil {
        log.Println(err, conn.RemoteAddr())
        return err
      }
    }
    currentMessage := ParseJSON(scanr.Bytes())

The problem is that the server does not understand when the data transmitted by the client ends and waits until the client closes the connection or until the buffer overflows. In the case of strings, it was enough to pass the end-of-line character "\n", but what to do in the case of []byte is not clear.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question