From 3dd1778332eff415d6f65328c3e2b1991c49aa21 Mon Sep 17 00:00:00 2001 From: Javier Sancho Date: Tue, 12 Dec 2017 17:31:30 +0100 Subject: [PATCH] Add telnet file with support to send and receive text from Merc MUD --- telnet.go | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 telnet.go diff --git a/telnet.go b/telnet.go new file mode 100644 index 0000000..f674e01 --- /dev/null +++ b/telnet.go @@ -0,0 +1,90 @@ +/* +midgaard_bot, a Telegram bot which sets a bridge to Midgaard Merc MUD +Copyright (C) 2017 by Javier Sancho Fernandez + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +package main + +import ( + "bytes" + "time" + + "github.com/reiver/go-oi" + "github.com/reiver/go-telnet" +) + +type TelnetCaller struct { + Input chan string + Output chan string +} + +func (caller TelnetCaller) CallTELNET(ctx telnet.Context, writer telnet.Writer, reader telnet.Reader) { + + // Send text to MUD + go func() { + var buffer bytes.Buffer + var p []byte + + crlfBuffer := [2]byte{'\r', '\n'} + crlf := crlfBuffer[:] + + for { + message := <-caller.Input + buffer.Write([]byte(message)) + buffer.Write(crlf) + + p = buffer.Bytes() + oi.LongWrite(writer, p) + buffer.Reset() + } + }() + + // Receive text from MUD + chunks := make(chan string) + chunk := "" + + go func() { + var buffer [1]byte + p := buffer[:] + + for { + n, err := reader.Read(p) + if n <= 0 && err == nil { + continue + } else if n <= 0 && err != nil { + break + } + + chunks <- string(p) + } + }() + + for { + select { + case input := <-chunks: + chunk = input + for chunk != "" { + select { + case input := <-chunks: + chunk = chunk + input + case <-time.After(time.Millisecond * 500): + caller.Output <- chunk + chunk = "" + } + } + } + } +} -- 2.39.2