目录
摘要:
记录使用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
}
}
}
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
}
}
}
本内容为合法授权发布,文章内容为作者独立观点,不代表开发云立场,未经允许不得转载。