works:programmer:go:telnet-server
GoLang Telnet сервер с timeout
package main import ( "net" "fmt" "io" "time" "strings" ) func main() { if listener, err := net.Listen("tcp", ":7723"); err == nil { for { if conn, err := listener.Accept(); err == nil { go onConnect(conn) } } } } func send(conn net.Conn, str string) { str = strings.Replace(str, "\r", "\\r", -1) str = strings.Replace(str, "\n", "\\n", -1) str = strings.Replace(str, "\t", "\\t", -1) str = strings.Trim(str, " \r\n\t") + "\r\n" conn.Write([]byte(str)) } func onCommand(conn net.Conn, command string) (bool, error) { command = strings.Trim(command, " \t\r\n") commandLower := strings.ToLower(command) if commandLower == "quit" { return true, nil } fmt.Println(command) send(conn, command) return false, nil } func onConnect(conn net.Conn) { defer conn.Close() send(conn, "Goodie Console - Welcome! v14.0.1b") line := "" buffer := make([]byte, 1024) conn.SetReadDeadline(time.Now().Add(60 * time.Second)) for { if bufferlen, err := conn.Read(buffer); err == nil && bufferlen > 0 { conn.SetReadDeadline(time.Now().Add(60 * time.Second)) // set input timeout for i := 0; i<bufferlen; i++ { switch buffer[i] { case 13: break case 10: if close, err := onCommand(conn, line); close { return } else if err != nil { // log error to log } line = "" break case 9: if len(line) > 0 { line = line[ 0 : len(line)-1 ] } default: line += string(buffer[i]) break } } } else if err == io.EOF { fmt.Println("detected closed LAN connection") return } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() { fmt.Println("detected connection timed out") return } else { // log error } } }
works/programmer/go/telnet-server.txt · Последнее изменение: 2019/02/21 08:28 — 127.0.0.1