v2ray-core/testing/servers/udp/udp.go

53 lines
1.2 KiB
Go
Raw Normal View History

2015-10-04 18:22:52 +00:00
package udp
import (
"fmt"
"v2ray.com/core/common/net"
2015-10-04 18:22:52 +00:00
)
type Server struct {
Port net.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
}
func (server *Server) Start() (net.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 {
return net.Destination{}, err
2015-10-04 18:22:52 +00:00
}
server.Port = net.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)
return net.UDPDestination(net.IPAddress(localAddr.IP), net.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])
2017-05-03 09:33:42 +00:00
if _, err := conn.WriteToUDP(response, addr); err != nil {
fmt.Println("Failed to write to UDP: ", err.Error())
}
2015-10-04 18:22:52 +00:00
}
}
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
}