55 lines
856 B
Go
55 lines
856 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"log"
|
||
|
"net"
|
||
|
"os"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
HOST = "localhost"
|
||
|
PORT = "8080"
|
||
|
TYPE = "tcp"
|
||
|
)
|
||
|
|
||
|
var clients []Client
|
||
|
|
||
|
func main() {
|
||
|
listen, err := net.Listen(TYPE, HOST+":"+PORT)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
os.Exit(1)
|
||
|
}
|
||
|
// close listener
|
||
|
defer listen.Close()
|
||
|
for {
|
||
|
conn, err := listen.Accept()
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
os.Exit(1)
|
||
|
}
|
||
|
go handleRequest(conn)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func handleRequest(conn net.Conn) {
|
||
|
for {
|
||
|
// incoming request
|
||
|
buffer := make([]byte, 1024)
|
||
|
_, err := conn.Read(buffer)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
// write data to response
|
||
|
timeString := time.Now().Format(time.ANSIC)
|
||
|
responseStr := fmt.Sprintf("Your message is: %v. Received timeString: %v", string(buffer[:]), timeString)
|
||
|
_, err = conn.Write([]byte(responseStr))
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
}
|
||
|
}
|