1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-23 18:46:49 -05:00
v2fly/testing/servers/udp/udp.go

51 lines
1.1 KiB
Go
Raw Normal View History

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{
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 {
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
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
}