-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathudp.go
58 lines (45 loc) · 1.02 KB
/
udp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package http
import (
"io"
"syscall"
)
// UDPClient is an interface for the UDP client
type UDPClient interface {
// SendTo sends data.
SendTo(data []byte, ip [4]byte, port int) error
// Recvfrom returns io.Reader
Recvfrom() (io.Reader, error)
// Close closes the connection.
Close() error
}
// NewUDPClient creates a client
func NewUDPClient() UDPClient {
return &udpClient{}
}
type udpClient struct {
socket int
}
func (c *udpClient) SendTo(data []byte, ip [4]byte, port int) error {
socket, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_DGRAM, 0)
if err != nil {
return err
}
c.socket = socket
return syscall.Sendto(socket, data, 0, sockaddr(ip, port))
}
func (c *udpClient) Recvfrom() (io.Reader, error) {
return &receiver{c.socket}, nil
}
func (c *udpClient) Close() error {
return syscall.Close(c.socket)
}
type receiver struct {
socket int
}
func (r *receiver) Read(buf []byte) (int, error) {
n, _, err := syscall.Recvfrom(r.socket, buf, 0)
if err != nil {
return 0, err
}
return n, io.EOF
}