reiver / go-telnet

Package telnet provides TELNET and TELNETS client and server implementations, for the Go programming language, in a style similar to the "net/http" library that is part of the Go standard library, including support for "middleware"; TELNETS is secure TELNET, with the TELNET protocol over a secured TLS (or SSL) connection.
https://godoc.org/github.com/reiver/go-telnet
MIT License
263 stars 83 forks source link

Is there a ReadString ('\ n')? #19

Closed muzudho closed 3 years ago

muzudho commented 3 years ago

Hi!

Is there a ReadString ('\ n')?

There is Read(p). https://godoc.org/github.com/reiver/go-telnet

'\ n' does not return.

Thank you.

muzudho commented 3 years ago

The server did not send a line break.

Self-solved by separating read and write with goroutine.

package main

import (
    "bufio"
    "os"

    "github.com/reiver/go-oi"
    "github.com/reiver/go-telnet"
)

func startClient() error {
    return telnet.DialToAndCall("localhost:9696", clientListener{})
}

type clientListener struct{}

// CallTELNET
func (c clientListener) CallTELNET(ctx telnet.Context, w telnet.Writer, r telnet.Reader) {
    go read(r)
    write(w)
}

// Loop semi-infinity.
func read(r telnet.Reader) {
    var buffer [1]byte // Until full.
    p := buffer[:]

    for {
        n, err := r.Read(p) // Blocking if server not send.

        if n > 0 {
            bytes := p[:n]
            print(string(bytes)) // 1 byte by step.
        }

        if nil != err {
            break // Disconnection, etc.
        }
    }
}

// Write everytime.
func write(w telnet.Writer) {
    scanner := bufio.NewScanner(os.Stdin)
    // Monitoring input. Scan line.
    for scanner.Scan() {
        // Put newline at end.
        oi.LongWrite(w, scanner.Bytes())
        oi.LongWrite(w, []byte("\n"))
    }
}
cesarvspr commented 2 years ago

I think this should be reopened, "\n" should be a considerable string.