working telnet echo server

main
Nick Dumas 1 week ago
parent b4e7c1c0a8
commit 7a4d66bcf8

@ -66,7 +66,12 @@ func (a *App) Run(ctx context.Context) {
s := NewServer(ctx, a.L, a.Config.Port) s := NewServer(ctx, a.L, a.Config.Port)
go s.Start() go s.Start()
for session := range s.Sessions { for {
go session.Start() select {
case <-ctx.Done():
return
case session := <-s.Sessions:
go session.Start()
}
} }
} }

@ -6,6 +6,8 @@ import (
"fmt" "fmt"
"log/slog" "log/slog"
"net" "net"
"github.com/google/uuid"
) )
type Server struct { type Server struct {
@ -64,31 +66,47 @@ type Session struct {
} }
func NewSession(ctx context.Context, c net.Conn, p Printer, l *slog.Logger) *Session { func NewSession(ctx context.Context, c net.Conn, p Printer, l *slog.Logger) *Session {
sid := uuid.New()
return &Session{ return &Session{
ctx: ctx, ctx: ctx,
l: l, l: l.With(slog.String("sid", sid.String())),
p: p,
c: c, c: c,
} }
} }
func (s *Session) bufferInput(commands chan string) {
scanner := bufio.NewScanner(s.c)
defer close(commands)
for scanner.Scan() {
err := scanner.Err()
switch err {
case nil:
commands <- scanner.Text()
default:
s.l.With(slog.Any("error", scanner.Err())).Error("error scanning input")
return
}
}
s.l.Debug("session terminated")
}
func (s *Session) Start() { func (s *Session) Start() {
s.l.Debug("starting telnet session") s.l.Debug("starting telnet session")
fmt.Fprint(s.c, "Welcome to Bing Bong.\n") fmt.Fprint(s.c, "Welcome to Bing Bong.\n")
scanner := bufio.NewScanner(s.c)
var line string commands := make(chan string)
for { go s.bufferInput(commands)
select {
case <-s.ctx.Done(): for command := range commands {
s.l.Error("cancelled") s.l.With(slog.String("command", command)).Debug("command recieved")
_, err := fmt.Fprintf(s.c, "> %q\n", command)
if err != nil {
s.l.With(
slog.Any("error", err),
).Error("connection closed on write")
return return
default:
if scanner.Scan() {
line = scanner.Text()
fmt.Fprintf(s.c, "> %q\n", line)
}
// a.L.Info("scanning input")
s.l.With(slog.String("input", line)).Info("received command")
} }
} }
} }

Loading…
Cancel
Save