2015-10-04 14:22:52 -04:00
|
|
|
package udp
|
|
|
|
|
|
|
|
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
|
2016-02-03 06:18:52 -05:00
|
|
|
conn *net.UDPConn
|
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
|
|
|
conn, err := net.ListenUDP("udp", &net.UDPAddr{
|
|
|
|
IP: []byte{0, 0, 0, 0},
|
|
|
|
Port: int(server.Port),
|
|
|
|
Zone: "",
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2016-02-02 10:03:56 -05:00
|
|
|
server.conn = conn
|
2015-10-04 14:22:52 -04:00
|
|
|
go server.handleConnection(conn)
|
|
|
|
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
2015-12-16 17:53:38 -05:00
|
|
|
return v2net.UDPDestination(v2net.IPAddress(localAddr.IP), v2net.Port(localAddr.Port)), nil
|
2015-10-04 14:22:52 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
func (server *Server) handleConnection(conn *net.UDPConn) {
|
2015-12-15 10:00:47 -05:00
|
|
|
server.accepting = true
|
|
|
|
defer conn.Close()
|
2015-10-04 14:22:52 -04:00
|
|
|
for {
|
|
|
|
buffer := make([]byte, 2*1024)
|
|
|
|
nBytes, addr, err := conn.ReadFromUDP(buffer)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to read from UDP: %v\n", err)
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
response := server.MsgProcessor(buffer[:nBytes])
|
|
|
|
conn.WriteToUDP(response, addr)
|
|
|
|
}
|
|
|
|
}
|
2015-12-15 10:00:47 -05:00
|
|
|
|
|
|
|
func (server *Server) Close() {
|
|
|
|
server.accepting = false
|
2016-02-02 10:03:56 -05:00
|
|
|
server.conn.Close()
|
2015-12-15 10:00:47 -05:00
|
|
|
}
|