main.go 901 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "net"
  6. "time"
  7. "git.chuangxin1.com/csacred/toolkit/tcp"
  8. )
  9. func main() {
  10. tcp.NewTCPServer(":2020", func(conn *net.TCPConn) {
  11. defer conn.Close()
  12. conn.SetNoDelay(true)
  13. //conn.SetKeepAlive(keepalive)
  14. //bufr := bufio.NewReader(conn)
  15. var buf = make([]byte, 4096)
  16. for {
  17. conn.SetReadDeadline(time.Now().Add(time.Second * 10))
  18. //n, err := bufr.Read(buf)
  19. n, err := conn.Read(buf)
  20. if err != nil {
  21. if err == io.EOF {
  22. fmt.Println("EOF")
  23. } else if operr, ok := err.(*net.OpError); ok {
  24. fmt.Println("net.OpError")
  25. if operr.Timeout() {
  26. fmt.Println("I/O timeout: ", conn.RemoteAddr().String(), time.Now().Format("2006-01-02 15:04:05"))
  27. continue
  28. }
  29. }
  30. fmt.Println("err:", err)
  31. break
  32. }
  33. fmt.Printf("Read %d bytes\n", n)
  34. conn.Write(buf[:n])
  35. }
  36. println("End ", conn.RemoteAddr().String())
  37. })
  38. }