54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"log"
|
||
|
"net"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
|
listenerAddr, err := net.ResolveTCPAddr("tcp4", ":6699")
|
||
|
if err != nil {
|
||
|
log.Fatalf("could not resolve listenAddr: %v", err)
|
||
|
}
|
||
|
|
||
|
listener, err := net.ListenTCP("tcp", listenerAddr)
|
||
|
if err != nil {
|
||
|
log.Fatalf("could not listen on address '%s': %v", listenerAddr.String(), err)
|
||
|
}
|
||
|
|
||
|
for {
|
||
|
conn, err := listener.Accept()
|
||
|
if err != nil {
|
||
|
log.Printf("failed to accept new incoming connection: %v", err) // if logging facility has latency this will block
|
||
|
continue
|
||
|
}
|
||
|
go connHandler(conn) // branch off into goroutine so we're not blocking
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func connHandler(conn net.Conn) {
|
||
|
log.Printf("accepted new connection from: %s", conn.RemoteAddr().String())
|
||
|
|
||
|
conn.SetReadDeadline(time.Now().Add(time.Second))
|
||
|
|
||
|
for {
|
||
|
|
||
|
buf := make([]byte, 128)
|
||
|
bytesRead, err := conn.Read(buf)
|
||
|
if err == nil && bytesRead > 0 {
|
||
|
log.Printf("Incoming message over socket '%s': %s", conn.RemoteAddr().String(), string(buf))
|
||
|
}
|
||
|
|
||
|
_, err = conn.Write([]byte("1"))
|
||
|
if err != nil {
|
||
|
log.Printf("failed writing to connection '%s': %v", conn.RemoteAddr().String(), err)
|
||
|
conn.Close()
|
||
|
break
|
||
|
}
|
||
|
|
||
|
time.Sleep(time.Second)
|
||
|
}
|
||
|
|
||
|
}
|