コード例 #1
0
ファイル: tcpudp.go プロジェクト: xiaobagou/echo
func handleTCPConn(tcpconn *net.TCPConn, encryptKey []byte, buffer *bytes.Buffer, bpool *bpool.SizedBufferPool) {
	defer tcpconn.Close()
	defer bpool.Put(buffer)
	var receiveData []byte
	//tcpconn need read all data in 20 second ,otherwise Timeout() will be true
	tcpconn.SetReadDeadline(time.Now().Add(time.Duration(20) * time.Second))
	bufReader := bufio.NewReader(tcpconn)
	for {
		rData, err := bufReader.ReadBytes(',')
		if err != nil {
			if err == io.EOF {
				log.Printf("TCPConn Read error\n")
				return
			}
			buffer.Write(rData)
			continue
		}

		buffer.Write(rData)

		receiveData, err = netstring.Unmarshall(buffer.Bytes())
		if err != nil {
			if err == netstring.ErrNsLenNotEqaulOrgLen {
				continue
			} else {
				log.Printf("netstring unmarshall error : %v\n", err)
				return
			}
		}

		break
	}

	_, err := libsodium.DecryptData(encryptKey, receiveData)
	if err != nil {
		log.Printf("tcp DecryptData error : %v\n", err)
		return
	}

	tcpconn.SetWriteDeadline(time.Now().Add(time.Duration(20) * time.Second))
	_, err = tcpconn.Write(netstring.Marshall([]byte(homeip)))
	if err != nil {
		log.Printf("tcpconn error : %v\n", err)
	}
}
コード例 #2
0
ファイル: tcpudp.go プロジェクト: xiaobagou/echo
func handleUDPConn(udpconn *net.UDPConn, key []byte, receiveData []byte) {
	//udpconn.SetReadDeadline(time.Now().Add(time.Duration(20) * time.Second))
	receiveDatalen, addr, err := udpconn.ReadFrom(receiveData)
	if err != nil {
		log.Printf("udpconn ReadFrom err : %v\n", err)
	}

	receiveData, err = netstring.Unmarshall(receiveData[:receiveDatalen])
	if err != nil {
		log.Printf("netstring unmarshall error : %v\n", err)
		return
	}

	_, err = libsodium.DecryptData(key, receiveData)
	if err != nil {
		log.Printf("udp DecryptData error : %v\n", err)
		return
	}

	homeip = addr.String()
}