2015-10-04 18:22:52 +00:00
|
|
|
package udp
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
|
2016-08-20 18:55:45 +00:00
|
|
|
v2net "v2ray.com/core/common/net"
|
2015-10-04 18:22:52 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
2015-12-02 20:44:01 +00:00
|
|
|
Port v2net.Port
|
2015-10-04 18:22:52 +00:00
|
|
|
MsgProcessor func(msg []byte) []byte
|
2015-12-15 15:00:47 +00:00
|
|
|
accepting bool
|
2016-02-03 11:18:52 +00:00
|
|
|
conn *net.UDPConn
|
2015-10-04 18:22:52 +00:00
|
|
|
}
|
|
|
|
|
2015-12-16 22:53:38 +00:00
|
|
|
func (server *Server) Start() (v2net.Destination, error) {
|
2015-10-04 18:22:52 +00:00
|
|
|
conn, err := net.ListenUDP("udp", &net.UDPAddr{
|
2016-05-29 14:37:52 +00:00
|
|
|
IP: []byte{127, 0, 0, 1},
|
2015-10-04 18:22:52 +00:00
|
|
|
Port: int(server.Port),
|
|
|
|
Zone: "",
|
|
|
|
})
|
|
|
|
if err != nil {
|
2016-09-20 09:53:05 +00:00
|
|
|
return v2net.Destination{}, err
|
2015-10-04 18:22:52 +00:00
|
|
|
}
|
2016-08-15 20:12:11 +00:00
|
|
|
server.Port = v2net.Port(conn.LocalAddr().(*net.UDPAddr).Port)
|
2016-02-02 15:03:56 +00:00
|
|
|
server.conn = conn
|
2015-10-04 18:22:52 +00:00
|
|
|
go server.handleConnection(conn)
|
|
|
|
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
2015-12-16 22:53:38 +00:00
|
|
|
return v2net.UDPDestination(v2net.IPAddress(localAddr.IP), v2net.Port(localAddr.Port)), nil
|
2015-10-04 18:22:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (server *Server) handleConnection(conn *net.UDPConn) {
|
2015-12-15 15:00:47 +00:00
|
|
|
server.accepting = true
|
2016-05-02 21:02:40 +00:00
|
|
|
for server.accepting {
|
2015-10-04 18:22:52 +00: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])
|
|
|
|
conn.WriteToUDP(response, addr)
|
|
|
|
}
|
|
|
|
}
|
2015-12-15 15:00:47 +00:00
|
|
|
|
|
|
|
func (server *Server) Close() {
|
|
|
|
server.accepting = false
|
2016-02-02 15:03:56 +00:00
|
|
|
server.conn.Close()
|
2015-12-15 15:00:47 +00:00
|
|
|
}
|