forked from organization/VRakLib
-
Notifications
You must be signed in to change notification settings - Fork 1
/
udpsocket.v
62 lines (55 loc) · 1.55 KB
/
udpsocket.v
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
59
60
61
62
module vraklib
import net
const (
default_buffer_size = 8388608 // 1024 * 1024 * 8
)
struct UdpSocket {
mut:
s net.UdpConn
}
pub fn create_socket(address string) ?UdpSocket {
// s := net.socket_udp() or { panic(err) }
// // level, optname, optvalue
// bufsize := default_buffer_size
// s.setsockopt(C.SOL_SOCKET, C.SO_RCVBUF, &bufsize)
// zero := 0
// s.setsockopt(C.SOL_SOCKET, C.SO_REUSEADDR, &zero)
// s.bind( port ) or { panic(err) }
//mut conn := net.listen_udp(port) or { panic(err) }
mut conn := net.listen_udp(address) or {panic(err)}
return UdpSocket{conn}
}
fn (s UdpSocket) receive() ?Packet {
bufsize := default_buffer_size
mut c := s.s
mut buf := []u8{len: bufsize, init: 0}
read, addr := c.read(mut buf) or { return none }
println('Got address $addr')
// println('Got $read bytes')
// println('Got ${buf.data} bytes')
return Packet{
buffer: new_bytebuffer(buf, u32(read))
address: addr.addr.Ip
}
}
fn (mut s UdpSocket) send(p Packet) ?int {
// TODO - seems to be incomplete in vlang
// mut addr := C.sockaddr_in{}
// addr.sin_port = int(p.address.port)
// C.inet_pton(C.AF_INET, p.address.ip.str, &addr.sin_addr)//TODO look up what this is
// buffer := p.buffer.buffer
// length := p.buffer.length
// size := 16
// res := int(C.sendto(s.s.sockfd, buffer, length, 0, &addr, size))//TODO find vlang method
// if res == -1 {
// return error('Could not send the packet')
// }
// return res
println('UdpSocket send')
println(p.address)
p.buffer.print()
return none
}
fn (mut s UdpSocket) close() {
s.s.close() or { panic(err) }
}