JLine the contract for NonBlockingReader seems bro

2019-09-02 05:39发布

问题:

Follows on from my previous question about JLine. OS: W10, using Cygwin.

def terminal = org.jline.terminal.TerminalBuilder.builder().jna( true ).system( true ).build()
terminal.enterRawMode()
// NB the Terminal I get is class org.jline.terminal.impl.PosixSysTerminal
def reader = terminal.reader()
// class org.jline.utils.NonBlocking$NonBlockingInputStreamReader

def bytes = [] // NB class ArrayList
int readInt = -1
while( readInt != 13 && readInt != 10 ) {
    readInt = reader.read()
    byte convertedByte = (byte)readInt
    // see what the binary looks like:
    String binaryString = String.format("%8s", Integer.toBinaryString( convertedByte & 0xFF)).replace(' ', '0')
    println "binary |$binaryString|"
    bytes << (byte)readInt // NB means "append to list"

    // these seem to block forever, whatever the param... 
    // int peek = reader.peek( 50 ) 
    int peek = reader.peek( 0 )

}
// strip final byte (13 or 10)
bytes = bytes[0..-2]
def response = new String( (byte[])bytes.toArray(), 'UTF-8' )

According to the Javadoc (made locally from the source) peek looks like this:

public int peek(long timeout)

Peeks to see if there is a byte waiting in the input stream without actually consuming the byte.

Parameters: timeout - The amount of time to wait, 0 == forever Returns: -1 on eof, -2 if the timeout expired with no available input or the character that was read (without consuming it).

It doesn't say what time units are involved here... I assume milliseconds, but I also tried with "1", just in case it's seconds.

This peek command is sufficiently functional as it stands for you to be able to detect multi-byte Unicode input, with a bit of time-out ingenuity: one presumes the bytes of a multi-byte Unicode character will arrive faster than a person can type...

However, if it never unblocks this means that you have to put the peek command inside a time-out mechanism which you have to roll yourself. The next character input will of course unblock things. If this is an Enter the while loop will then end. But if, say, you wanted to print a character (or do anything) before the next character is input the fact that peek's timeout doesn't appear to work prevents you doing that.

回答1:

Try playing with

 jshell> "              
                            
标签: java peek jline3