server.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package microservice
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "net"
  7. "git.ali33.ru/fcg-xvii/go-tools/containers/concurrent"
  8. )
  9. func NewServer(host string, port uint16, sockBufSize int, ctx context.Context, receiveBuf int) *Server {
  10. ctx, cancel := context.WithCancel(ctx)
  11. server := &Server{
  12. ctx: ctx,
  13. cancel: cancel,
  14. host: host,
  15. port: port,
  16. chConnection: make(chan *Socket),
  17. sockets: concurrent.NewList(),
  18. receiveBuf: receiveBuf,
  19. }
  20. go server.start()
  21. return server
  22. }
  23. type Server struct {
  24. ctx context.Context
  25. cancel context.CancelFunc
  26. host string
  27. port uint16
  28. sockBufSize int
  29. receiveBuf int
  30. listener net.Listener
  31. sockets *concurrent.List
  32. chConnection chan *Socket
  33. }
  34. func (s *Server) NewConnection() <-chan *Socket {
  35. return s.chConnection
  36. }
  37. func (s *Server) start() {
  38. go s.listen()
  39. <-s.ctx.Done()
  40. s.listener.Close()
  41. close(s.chConnection)
  42. }
  43. func (s *Server) listen() {
  44. var err error
  45. if s.listener, err = net.Listen("tcp", fmt.Sprintf("%v:%v", s.host, s.port)); err != nil {
  46. log.Fatal("Error starting all trade server:", err)
  47. }
  48. var conn net.Conn
  49. for {
  50. if conn, err = s.listener.Accept(); err != nil {
  51. //fmt.Println("Error accepting connection:", err)
  52. return
  53. }
  54. socket := NewSocket(conn, s.sockBufSize, s.ctx, s.receiveBuf)
  55. s.sockets.PushBack(socket)
  56. go func(sock *Socket) {
  57. <-sock.Context().Done()
  58. log.Println("close sock accepted....")
  59. if elem := s.sockets.Search(sock); elem != nil {
  60. log.Println("socket remove from list")
  61. s.sockets.Remove(elem)
  62. }
  63. log.Println(s.sockets.Size())
  64. }(socket)
  65. s.chConnection <- socket
  66. }
  67. }
  68. func (s *Server) Close() {
  69. s.cancel()
  70. s.sockets.Each(func(val *concurrent.Element) bool {
  71. log.Println("CLOSE socket..........")
  72. val.Val().(*Socket).Close()
  73. return true
  74. })
  75. }