58 lines
879 B
Go
58 lines
879 B
Go
package sltcpsrv
|
|
|
|
import (
|
|
"bufio"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
isDebug = flag.Bool("d", false, "Turn on debugging")
|
|
)
|
|
|
|
func ListenAndServe(port int) {
|
|
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
log.Printf("Listening on %v\n", ln.Addr())
|
|
|
|
for {
|
|
conn, err := ln.Accept()
|
|
if err != nil {
|
|
log.Printf("WARN: Failed to accept connection!: %+v\n", err)
|
|
continue
|
|
}
|
|
|
|
go handleConnection(conn)
|
|
}
|
|
}
|
|
|
|
func handleConnection(conn net.Conn) {
|
|
defer conn.Close()
|
|
|
|
connBuf := bufio.NewReader(conn)
|
|
|
|
for {
|
|
line, err := connBuf.ReadString('\n')
|
|
if err != nil {
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
|
|
log.Printf("Failed to read line: %+v\n", err)
|
|
return
|
|
}
|
|
|
|
msg := newMessage([]byte(strings.TrimSpace(line)))
|
|
if msg != nil {
|
|
fmt.Printf("%v: %+v\n", conn.RemoteAddr(), msg)
|
|
}
|
|
}
|
|
}
|