package serf import ( "basic.com/valib/logger.git" "bufio" "bytes" "encoding/binary" "io" "net" "strconv" "vamicro/config" "vamicro/system-service/sys" ) func rawSendTcpMsg(addr string, sendBuf []byte) error { conn, err := net.Dial("tcp", addr) if err != nil { logger.Debug("net.Dialt err", err) return err } defer conn.Close() //发送 sizeBuf := make([]byte, 4) var buf bytes.Buffer binary.BigEndian.PutUint32(sizeBuf, uint32(len(sendBuf))) buf.Write(sizeBuf) buf.Write(sendBuf) _, err = conn.Write(buf.Bytes()) if err != nil { logger.Debug("conn.Write err", err) return err } else { logger.Debug("raw send success") return nil } } func RawReceiveTcpMsg() { localIp, _, _ := sys.GetLocalIP(config.Server.NetworkAdapter) if localIp == "" { localIp = "0.0.0.0" } tcpAddr := localIp + ":" + strconv.Itoa(TcpTransportPort) listener, err := net.Listen("tcp", tcpAddr) if err != nil { logger.Debug("RawReceive server listen err:", err) return } defer listener.Close() for { conn, err := listener.Accept() if err != nil { logger.Debug("listener.Accept err:", err) continue } logger.Debug("A transport client connected :" + conn.RemoteAddr().String()) go readStream(conn) } } func readStream(conn net.Conn) { defer conn.Close() var data []byte var reader io.Reader = bufio.NewReader(conn) sizeBuf := make([]byte, 4) if _, err := reader.Read(sizeBuf[:]); err != nil { logger.Debug("read tcpStream msg length err:", err) } else { var msgLen uint32 binary.Read(bytes.NewBuffer(sizeBuf), binary.BigEndian, &msgLen) dataLen := int(msgLen) logger.Debug("read tcpStream msg lenth:", dataLen) if dataLen > 0 { data = make([]byte, dataLen) n, err := io.ReadAtLeast(reader, data, dataLen) if err == nil { logger.Debug("io.ReadAtLeast n:", n) } else { logger.Debug("io.readAtLeast err:", err) } } } QueryTcpResponseChan <- data }