2015-10-04 14:22:52 -04:00
|
|
|
package tcp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
|
2016-08-20 14:55:45 -04:00
|
|
|
v2net "v2ray.com/core/common/net"
|
2015-10-04 14:22:52 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2015-12-02 15:44:01 -05:00
|
|
|
Port v2net.Port
|
2015-10-04 14:22:52 -04:00
|
|
|
MsgProcessor func(msg []byte) []byte
|
2016-08-20 03:12:44 -04:00
|
|
|
SendFirst []byte
|
2015-12-15 10:00:47 -05:00
|
|
|
accepting bool
|
2016-02-03 06:18:52 -05:00
|
|
|
listener *net.TCPListener
|
2015-10-04 14:22:52 -04:00
|
|
|
}
|
|
|
|
|
2015-12-16 17:53:38 -05:00
|
|
|
func (server *Server) Start() (v2net.Destination, error) {
|
2015-10-04 14:22:52 -04:00
|
|
|
listener, err := net.ListenTCP("tcp", &net.TCPAddr{
|
2016-05-29 10:37:52 -04:00
|
|
|
IP: []byte{127, 0, 0, 1},
|
2015-10-04 14:22:52 -04:00
|
|
|
Port: int(server.Port),
|
|
|
|
Zone: "",
|
|
|
|
})
|
|
|
|
if err != nil {
|
2016-09-20 05:53:05 -04:00
|
|
|
return v2net.Destination{}, err
|
2015-10-04 14:22:52 -04:00
|
|
|
}
|
2016-08-15 16:12:11 -04:00
|
|
|
server.Port = v2net.Port(listener.Addr().(*net.TCPAddr).Port)
|
2016-02-02 10:03:56 -05:00
|
|
|
server.listener = listener
|
2015-10-04 14:22:52 -04:00
|
|
|
go server.acceptConnections(listener)
|
|
|
|
localAddr := listener.Addr().(*net.TCPAddr)
|
2015-12-16 17:53:38 -05:00
|
|
|
return v2net.TCPDestination(v2net.IPAddress(localAddr.IP), v2net.Port(localAddr.Port)), nil
|
2015-10-04 14:22:52 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (server *Server) acceptConnections(listener *net.TCPListener) {
|
2015-12-15 10:00:47 -05:00
|
|
|
server.accepting = true
|
|
|
|
for server.accepting {
|
2015-10-04 14:22:52 -04:00
|
|
|
conn, err := listener.Accept()
|
|
|
|
if err != nil {
|
2016-11-10 17:41:28 -05:00
|
|
|
fmt.Printf("Failed accept TCP connection: %v\n", err)
|
2015-10-04 14:22:52 -04:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
go server.handleConnection(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (server *Server) handleConnection(conn net.Conn) {
|
2016-08-20 03:12:44 -04:00
|
|
|
if len(server.SendFirst) > 0 {
|
|
|
|
conn.Write(server.SendFirst)
|
|
|
|
}
|
2016-07-17 06:18:34 -04:00
|
|
|
request := make([]byte, 4096)
|
2015-12-15 10:00:47 -05:00
|
|
|
for true {
|
2016-07-17 06:18:34 -04:00
|
|
|
nBytes, err := conn.Read(request)
|
2015-12-15 10:00:47 -05:00
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
2016-07-17 06:18:34 -04:00
|
|
|
response := server.MsgProcessor(request[:nBytes])
|
2015-12-15 10:00:47 -05:00
|
|
|
conn.Write(response)
|
2015-10-04 14:22:52 -04:00
|
|
|
}
|
|
|
|
conn.Close()
|
|
|
|
}
|
2015-12-15 10:00:47 -05:00
|
|
|
|
2016-11-27 15:39:09 -05:00
|
|
|
func (v *Server) Close() {
|
|
|
|
v.accepting = false
|
|
|
|
v.listener.Close()
|
2015-12-15 10:00:47 -05:00
|
|
|
}
|