You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
50 lines
1.3 KiB
50 lines
1.3 KiB
package main
|
|
|
|
import (
|
|
"net"
|
|
"time"
|
|
)
|
|
|
|
// Connection represents a network socket.
|
|
type Connection struct {
|
|
dialer net.Dialer
|
|
socket net.Conn
|
|
connectTimeout time.Duration
|
|
readTimeout time.Duration
|
|
protocol string
|
|
}
|
|
|
|
// NewConnection creates a Connection object.
|
|
func NewConnection() *Connection {
|
|
conn := Connection{}
|
|
conn.connectTimeout = getParamDurationMS("connect-timeout-ms")
|
|
conn.readTimeout = getParamDurationMS("read-timeout-ms")
|
|
conn.protocol = "tcp"
|
|
return &conn
|
|
}
|
|
|
|
// Connect initiates a connection to an Endpoint.
|
|
func (conn *Connection) Connect(endpoint *Endpoint) (err error) {
|
|
conn.dialer = net.Dialer{Timeout: conn.connectTimeout, KeepAlive: -1}
|
|
conn.socket, err = conn.dialer.Dial(conn.protocol, endpoint.String())
|
|
if err != nil {
|
|
log("conn", 2, "cannot connect to \"%v\": %v", endpoint, err.Error())
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
// SetConnectTimeout sets a custom connect timeout on a Connection.
|
|
func (conn *Connection) SetConnectTimeout(timeout time.Duration) {
|
|
conn.connectTimeout = timeout
|
|
}
|
|
|
|
// SetReadTimeout sets a custom read timeout on a Connection.
|
|
func (conn *Connection) SetReadTimeout(timeout time.Duration) {
|
|
conn.readTimeout = timeout
|
|
}
|
|
|
|
// Send writes data to a Connection.
|
|
func (conn *Connection) Send(data []byte) {
|
|
conn.socket.SetReadDeadline(time.Now().Add(conn.readTimeout))
|
|
}
|
|
|