1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-12 15:27:16 -05:00
v2fly/testing/servers/tcp/tcp.go

59 lines
1.2 KiB
Go
Raw Normal View History

2015-10-04 14:22:52 -04:00
package tcp
import (
"fmt"
"net"
v2net "github.com/v2ray/v2ray-core/common/net"
)
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
2015-12-15 10:00:47 -05:00
accepting bool
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{
IP: []byte{0, 0, 0, 0},
Port: int(server.Port),
Zone: "",
})
if err != nil {
return nil, err
}
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
defer listener.Close()
for server.accepting {
2015-10-04 14:22:52 -04:00
conn, err := listener.Accept()
if err != nil {
fmt.Printf("Failed accept TCP connection: %v", err)
continue
}
go server.handleConnection(conn)
}
}
func (server *Server) handleConnection(conn net.Conn) {
2015-12-15 10:00:47 -05:00
for true {
request, err := v2net.ReadFrom(conn, nil)
if err != nil {
break
}
response := server.MsgProcessor(request.Value)
conn.Write(response)
2015-10-04 14:22:52 -04:00
}
conn.Close()
}
2015-12-15 10:00:47 -05:00
func (this *Server) Close() {
this.accepting = true
}