package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"time"
)

// go run exampleClock.go -p 8010 -loc Asia/Tokyo

func main() {
	// 设置flag
	locstr := flag.String("loc", "Asia/Shanghai", "请输入完整的时区名称")
	listenstr := flag.String("p", "8000", "请输入监听端口")
	flag.Parse()
	// 设置时区
	loc, err := time.LoadLocation(*locstr)
	if err != nil {
		log.Fatal(err)
	}

	// 监听8000端口
	listener, err := net.Listen("tcp", ":"+*listenstr)
	if err != nil {
		log.Fatal(err)
	}

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Print(err) // e.g., connection aborted
			continue
		}
		//handleConn(conn) // handle one connection at a time
		// 在调用handleConn时加上go关键字，就可以同时处理多个客户端连接
		go handleConn(conn, loc) // handle connections concurrently
	}

}

var num = 0

func handleConn(c net.Conn, loc *time.Location) {
	num++
	defer c.Close()
	fmt.Println("handleConn", num)
	for {
		_, err := io.WriteString(c, time.Now().In(loc).Format("15:04:05"))
		if err != nil {
			return // e.g., client disconnected
		}
		time.Sleep(1 * time.Second)
	}
}
