Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Xaenalt opened this issue Apr 10, 2018 · 0 comments
Closed

Comments

@Xaenalt
Copy link

Xaenalt commented Apr 10, 2018

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)

	}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant