github.com/zhongdalu/gf@v1.0.0/g/net/gtcp/gtcp_server.go (about)

     1  // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package gtcp
     8  
     9  import (
    10  	"crypto/tls"
    11  	"errors"
    12  	"github.com/zhongdalu/gf/g/container/gmap"
    13  	"github.com/zhongdalu/gf/g/os/glog"
    14  	"github.com/zhongdalu/gf/g/util/gconv"
    15  	"net"
    16  )
    17  
    18  const (
    19  	gDEFAULT_SERVER = "default"
    20  )
    21  
    22  // TCP Server.
    23  type Server struct {
    24  	listen    net.Listener
    25  	address   string
    26  	handler   func(*Conn)
    27  	tlsConfig *tls.Config
    28  }
    29  
    30  // Map for name to server, for singleton purpose.
    31  var serverMapping = gmap.NewStrAnyMap()
    32  
    33  // GetServer returns the TCP server with specified <name>,
    34  // or it returns a new normal TCP server named <name> if it does not exist.
    35  // The parameter <name> is used to specify the TCP server
    36  func GetServer(name ...interface{}) *Server {
    37  	serverName := gDEFAULT_SERVER
    38  	if len(name) > 0 {
    39  		serverName = gconv.String(name[0])
    40  	}
    41  	return serverMapping.GetOrSetFuncLock(serverName, func() interface{} {
    42  		return NewServer("", nil)
    43  	}).(*Server)
    44  }
    45  
    46  // NewServer creates and returns a new normal TCP server.
    47  // The parameter <name> is optional, which is used to specify the instance name of the server.
    48  func NewServer(address string, handler func(*Conn), name ...string) *Server {
    49  	s := &Server{
    50  		address: address,
    51  		handler: handler,
    52  	}
    53  	if len(name) > 0 {
    54  		serverMapping.Set(name[0], s)
    55  	}
    56  	return s
    57  }
    58  
    59  // NewServerTLS creates and returns a new TCP server with TLS support.
    60  // The parameter <name> is optional, which is used to specify the instance name of the server.
    61  func NewServerTLS(address string, tlsConfig *tls.Config, handler func(*Conn), name ...string) *Server {
    62  	s := NewServer(address, handler, name...)
    63  	s.SetTLSConfig(tlsConfig)
    64  	return s
    65  }
    66  
    67  // NewServerKeyCrt creates and returns a new TCP server with TLS support.
    68  // The parameter <name> is optional, which is used to specify the instance name of the server.
    69  func NewServerKeyCrt(address, crtFile, keyFile string, handler func(*Conn), name ...string) *Server {
    70  	s := NewServer(address, handler, name...)
    71  	if err := s.SetTLSKeyCrt(crtFile, keyFile); err != nil {
    72  		glog.Error(err)
    73  	}
    74  	return s
    75  }
    76  
    77  // SetAddress sets the listening address for server.
    78  func (s *Server) SetAddress(address string) {
    79  	s.address = address
    80  }
    81  
    82  // SetHandler sets the connection handler for server.
    83  func (s *Server) SetHandler(handler func(*Conn)) {
    84  	s.handler = handler
    85  }
    86  
    87  // SetTlsKeyCrt sets the certificate and key file for TLS configuration of server.
    88  func (s *Server) SetTLSKeyCrt(crtFile, keyFile string) error {
    89  	tlsConfig, err := LoadKeyCrt(crtFile, keyFile)
    90  	if err != nil {
    91  		return err
    92  	}
    93  	s.tlsConfig = tlsConfig
    94  	return nil
    95  }
    96  
    97  // SetTlsConfig sets the TLS configuration of server.
    98  func (s *Server) SetTLSConfig(tlsConfig *tls.Config) {
    99  	s.tlsConfig = tlsConfig
   100  }
   101  
   102  // Close closes the listener and shutdowns the server.
   103  func (s *Server) Close() error {
   104  	return s.listen.Close()
   105  }
   106  
   107  // Run starts running the TCP Server.
   108  func (s *Server) Run() (err error) {
   109  	if s.handler == nil {
   110  		err = errors.New("start running failed: socket handler not defined")
   111  		glog.Error(err)
   112  		return
   113  	}
   114  	if s.tlsConfig != nil {
   115  		// TLS Server
   116  		s.listen, err = tls.Listen("tcp", s.address, s.tlsConfig)
   117  		if err != nil {
   118  			glog.Error(err)
   119  			return
   120  		}
   121  	} else {
   122  		// Normal Server
   123  		addr, err := net.ResolveTCPAddr("tcp", s.address)
   124  		if err != nil {
   125  			glog.Error(err)
   126  			return err
   127  		}
   128  		s.listen, err = net.ListenTCP("tcp", addr)
   129  		if err != nil {
   130  			glog.Error(err)
   131  			return err
   132  		}
   133  	}
   134  	for {
   135  		if conn, err := s.listen.Accept(); err != nil {
   136  			glog.Error(err)
   137  			return err
   138  		} else if conn != nil {
   139  			go s.handler(NewConnByNetConn(conn))
   140  		}
   141  	}
   142  }