当前位置: 首页 > 工具软件 > FastTCP > 使用案例 >

2022-03-08 使用go快速创建tcp服务器

闾丘霖
2023-12-01

目录

摘要:

核心函数:

创建监听listen:

等待新连接accept:

读取数据并处理:


摘要:

记录使用go快速创建tcp服务器

核心函数:

创建监听listen:

func (s *Service) ProxyServiceOpen() error {
	s.Logger.Info("Open ProxyServiceOpen ready")

	bindAddress := g_localIp + ":" + g_proxyPort
	ln, err := net.Listen("tcp", bindAddress)
	if err != nil {
		s.Logger.Error(fmt.Sprintf("Open Server net.Listen fail, err = %v", err))
		return fmt.Errorf("ProxyServiceOpen listen fail, err = %v", err)
	}

	s.Listener = ln

	go s.ProxyServiceServe()

	s.Logger.Info(fmt.Sprintf("ProxyServiceOpen net.Listen ok, proxyAddr = %s", bindAddress))
	return nil
}

等待新连接accept:

func (s *Service) ProxyServiceServe() {
	for {
		conn, err := s.Listener.Accept()
		if err, ok := err.(interface {
			Temporary() bool
		}); ok && err.Temporary() {
			continue
		}

		if nil != err {
			s.Logger.Error(fmt.Sprintf("ProxyServiceServe fail, Listener.Accept = %v", err))
			continue
		}

		go s.ProxyServiceHandle(conn)
	}
}

读取数据并处理:

func (s *Service) ProxyServiceHandle(conn net.Conn) {
	defer conn.Close()

	for {
		b, err := io.ReadAll(conn)
		if nil != err {
			s.Logger.Error(fmt.Sprintf("ProxyServiceHandle fail, io.ReadFull err = %v", err))
			return
		}

		byteLen := len(b)
		if 0 == byteLen {
			s.Logger.Info(fmt.Sprintf("ProxyServiceHandle ignore, 0 == byteLen"))
			return
		}

		byte_apply := b[1:]
		s.Logger.Info(fmt.Sprintf("ProxyServiceHandle ready ApplyByte, byteLen = %d", byteLen))

		err = s.ProxyServiceProcessByte(byte_apply)
		if nil != err {
			s.Logger.Error(fmt.Sprintf("ProxyServiceHandle fail, ProxyServiceProcessByte err = %v", err))
			continue
		}
	}
}

 类似资料: