2020-06-02 22:48:55 +08:00
|
|
|
package request
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2020-09-07 14:57:23 +08:00
|
|
|
func SendTCPRequest(port int, content []byte, timeout time.Duration) (string, error) {
|
2020-06-02 22:48:55 +08:00
|
|
|
c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
|
|
|
if err != nil {
|
2020-09-07 14:57:23 +08:00
|
|
|
return "", fmt.Errorf("connect to tcp server error: %v", err)
|
2020-06-02 22:48:55 +08:00
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
|
|
|
|
c.SetDeadline(time.Now().Add(timeout))
|
2020-09-07 14:57:23 +08:00
|
|
|
return sendRequestByConn(c, content)
|
2020-06-02 22:48:55 +08:00
|
|
|
}
|
|
|
|
|
2020-09-07 14:57:23 +08:00
|
|
|
func SendUDPRequest(port int, content []byte, timeout time.Duration) (string, error) {
|
|
|
|
c, err := net.Dial("udp", fmt.Sprintf("127.0.0.1:%d", port))
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("connect to udp server error: %v", err)
|
|
|
|
}
|
|
|
|
defer c.Close()
|
|
|
|
|
|
|
|
c.SetDeadline(time.Now().Add(timeout))
|
|
|
|
return sendRequestByConn(c, content)
|
|
|
|
}
|
|
|
|
|
|
|
|
func sendRequestByConn(c net.Conn, content []byte) (string, error) {
|
2020-06-02 22:48:55 +08:00
|
|
|
c.Write(content)
|
|
|
|
|
|
|
|
buf := make([]byte, 2048)
|
2020-09-07 14:57:23 +08:00
|
|
|
n, err := c.Read(buf)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("read error: %v", err)
|
2020-06-02 22:48:55 +08:00
|
|
|
}
|
|
|
|
return string(buf[:n]), nil
|
|
|
|
}
|