2016-01-28 16:08:32 +00:00
|
|
|
package hub
|
2016-01-27 21:11:31 +00:00
|
|
|
|
|
|
|
import (
|
2016-03-09 10:34:27 +00:00
|
|
|
"errors"
|
2016-01-27 21:11:31 +00:00
|
|
|
"net"
|
|
|
|
|
|
|
|
"github.com/v2ray/v2ray-core/common/log"
|
|
|
|
v2net "github.com/v2ray/v2ray-core/common/net"
|
|
|
|
)
|
|
|
|
|
2016-03-09 10:34:27 +00:00
|
|
|
var (
|
|
|
|
ErrorClosedConnection = errors.New("Connection already closed.")
|
|
|
|
)
|
|
|
|
|
2016-01-28 19:47:00 +00:00
|
|
|
type TCPHub struct {
|
2016-01-27 21:11:31 +00:00
|
|
|
listener *net.TCPListener
|
2016-04-27 21:01:31 +00:00
|
|
|
connCallback ConnectionHandler
|
2016-01-27 21:11:31 +00:00
|
|
|
accepting bool
|
|
|
|
}
|
|
|
|
|
2016-04-27 21:01:31 +00:00
|
|
|
func ListenTCP(port v2net.Port, callback ConnectionHandler) (*TCPHub, error) {
|
2016-01-27 21:11:31 +00:00
|
|
|
listener, err := net.ListenTCP("tcp", &net.TCPAddr{
|
|
|
|
IP: []byte{0, 0, 0, 0},
|
|
|
|
Port: int(port),
|
|
|
|
Zone: "",
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-01-28 19:47:00 +00:00
|
|
|
tcpListener := &TCPHub{
|
2016-01-27 21:11:31 +00:00
|
|
|
listener: listener,
|
|
|
|
connCallback: callback,
|
|
|
|
}
|
|
|
|
go tcpListener.start()
|
|
|
|
return tcpListener, nil
|
|
|
|
}
|
|
|
|
|
2016-01-28 19:47:00 +00:00
|
|
|
func (this *TCPHub) Close() {
|
2016-01-27 21:11:31 +00:00
|
|
|
this.accepting = false
|
|
|
|
this.listener.Close()
|
2016-03-09 10:34:27 +00:00
|
|
|
this.listener = nil
|
2016-01-27 21:11:31 +00:00
|
|
|
}
|
|
|
|
|
2016-01-28 19:47:00 +00:00
|
|
|
func (this *TCPHub) start() {
|
2016-01-27 21:11:31 +00:00
|
|
|
this.accepting = true
|
|
|
|
for this.accepting {
|
|
|
|
conn, err := this.listener.AcceptTCP()
|
|
|
|
if err != nil {
|
2016-02-18 10:36:21 +00:00
|
|
|
if this.accepting {
|
|
|
|
log.Warning("Listener: Failed to accept new TCP connection: ", err)
|
|
|
|
}
|
2016-01-27 21:11:31 +00:00
|
|
|
continue
|
|
|
|
}
|
2016-04-27 21:01:31 +00:00
|
|
|
go this.connCallback(&TCPConnection{
|
2016-01-27 21:11:31 +00:00
|
|
|
conn: conn,
|
|
|
|
listener: this,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-28 19:47:00 +00:00
|
|
|
func (this *TCPHub) recycle(conn *net.TCPConn) {
|
2016-01-27 21:11:31 +00:00
|
|
|
|
|
|
|
}
|