1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-12 07:19:01 -05:00
v2fly/testing/servers/udp/udp.go

56 lines
1.3 KiB
Go
Raw Normal View History

2015-10-04 14:22:52 -04:00
package udp
import (
"fmt"
2021-01-11 21:44:12 -05:00
2021-02-16 15:31:50 -05:00
"github.com/v2fly/v2ray-core/v4/common/net"
2015-10-04 14:22:52 -04:00
)
type Server struct {
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
}
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 {
return net.Destination{}, err
2015-10-04 14:22:52 -04:00
}
server.Port = net.Port(conn.LocalAddr().(*net.UDPAddr).Port)
2018-09-10 16:12:07 -04:00
fmt.Println("UDP server started on port ", server.Port)
2016-02-02 10:03:56 -05:00
server.conn = conn
2015-10-04 14:22:52 -04:00
go server.handleConnection(conn)
2015-10-04 14:22:52 -04:00
localAddr := conn.LocalAddr().(*net.UDPAddr)
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
2018-02-08 09:39:46 -05:00
func (server *Server) Close() error {
2015-12-15 10:00:47 -05:00
server.accepting = false
2018-02-08 09:39:46 -05:00
return server.conn.Close()
2015-12-15 10:00:47 -05:00
}