2015-10-04 14:22:52 -04:00
|
|
|
package udp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
2017-08-29 06:56:57 -04:00
|
|
|
"v2ray.com/core/common/net"
|
2015-10-04 14:22:52 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2017-08-29 06:56:57 -04:00
|
|
|
Port net.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
|
|
|
}
|
|
|
|
|
2017-08-29 06:56:57 -04:00
|
|
|
func (server *Server) Start() (net.Destination, error) {
|
2015-10-04 14:22:52 -04:00
|
|
|
conn, err := net.ListenUDP("udp", &net.UDPAddr{
|
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 {
|
2017-08-29 06:56:57 -04:00
|
|
|
return net.Destination{}, err
|
2015-10-04 14:22:52 -04:00
|
|
|
}
|
2017-08-29 06:56:57 -04:00
|
|
|
server.Port = net.Port(conn.LocalAddr().(*net.UDPAddr).Port)
|
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)
|
2017-08-29 06:56:57 -04:00
|
|
|
return net.UDPDestination(net.IPAddress(localAddr.IP), net.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
|
2016-05-02 17:02:40 -04:00
|
|
|
for server.accepting {
|
2015-10-04 14:22:52 -04:00
|
|
|
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])
|
2017-05-03 05:33:42 -04:00
|
|
|
if _, err := conn.WriteToUDP(response, addr); err != nil {
|
|
|
|
fmt.Println("Failed to write to UDP: ", err.Error())
|
|
|
|
}
|
2015-10-04 14:22:52 -04:00
|
|
|
}
|
|
|
|
}
|
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
|
|
|
}
|