Skip to content

More() does not always return true when reading from a socket with data left #261

Closed
@Xaenalt

Description

@Xaenalt

For reading JSON over a socket, one useful method is the Decoder.More() method. This seems to behave unusually though with sockets. The following code will close a connection immediately because Decoder.More() is false whereas in the standard library it will be true after NewDecoder() is called. Additionally, setting the loop test condition to !jsonReader.More() will cause it to work for a few iterations, but it will subsequently become true. It seems to bounce back and forth over several other tries, like putting the test condition at the end of the loop with a break statement. Can the behavior of Decoder.More() be improved?

This code was tested with generated JSON of the form:

# for i in {0..1000000}; do echo "{\"count\": \"$i\"}" >> 1mjson; done
# nc localhost 1234 < 1mjson
package main

import (
	"fmt"
	"net"

	"github.com/json-iterator/go"
)

var json = jsoniter.ConfigCompatibleWithStandardLibrary

func main() {
	addr := ":1234"
	tcpAddr, _ := net.ResolveTCPAddr("tcp4", addr)
	listener, _ := net.ListenTCP("tcp", tcpAddr)

	for {
		conn, err := listener.Accept()
		if err != nil {
			continue
		}

		go func(conn net.Conn) {
			defer conn.Close()
			jsonReader := json.NewDecoder(conn)

			// Print whether or not there is more in the socket
			fmt.Printf("More(): %v", jsonReader.More())

			for jsonReader.More() {
				var jsonMsg map[string]interface{}
				jsonReader.Decode(&jsonMsg)
				fmt.Println(jsonMsg)

			}
			fmt.Println("Deferred close of connection executing")
		}(conn)

	}

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions