tcp_connector.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package mhayaConnector
  2. import (
  3. cfacade "github.com/mhaya/facade"
  4. clog "github.com/mhaya/logger"
  5. )
  6. type (
  7. TCPConnector struct {
  8. cfacade.Component
  9. Connector
  10. Options
  11. }
  12. )
  13. func (*TCPConnector) Name() string {
  14. return "tcp_connector"
  15. }
  16. func (t *TCPConnector) OnAfterInit() {
  17. }
  18. func (t *TCPConnector) OnStop() {
  19. t.Stop()
  20. }
  21. func NewTCP(address string, opts ...Option) *TCPConnector {
  22. if address == "" {
  23. clog.Warn("Create tcp connector fail. Address is null.")
  24. return nil
  25. }
  26. tcp := &TCPConnector{
  27. Options: Options{
  28. address: address,
  29. certFile: "",
  30. keyFile: "",
  31. chanSize: 256,
  32. },
  33. }
  34. for _, opt := range opts {
  35. opt(&tcp.Options)
  36. }
  37. tcp.Connector = NewConnector(tcp.chanSize)
  38. return tcp
  39. }
  40. func (t *TCPConnector) Start() {
  41. listener, err := t.GetListener(t.certFile, t.keyFile, t.address)
  42. if err != nil {
  43. clog.Fatalf("failed to listen: %s", err)
  44. }
  45. clog.Infof("Tcp connector listening at Address %s", t.address)
  46. if t.certFile != "" || t.keyFile != "" {
  47. clog.Infof("certFile = %s, keyFile = %s", t.certFile, t.keyFile)
  48. }
  49. t.Connector.Start()
  50. for t.Running() {
  51. conn, err := listener.Accept()
  52. if err != nil {
  53. clog.Errorf("Failed to accept TCP connection: %s", err.Error())
  54. continue
  55. }
  56. t.InChan(conn)
  57. }
  58. }
  59. func (t *TCPConnector) Stop() {
  60. t.Connector.Stop()
  61. }