1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-06 10:20:44 -05:00
v2fly/testing/servers/udp/udp.go

52 lines
1.1 KiB
Go
Raw Normal View History

2015-10-04 14:22:52 -04:00
package udp
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
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{
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(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)
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
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])
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
}