-
Notifications
You must be signed in to change notification settings - Fork 3
/
comm.go
90 lines (71 loc) · 1.84 KB
/
comm.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package udpHeader
import (
"bytes"
"net"
"syscall"
"time"
)
import "math/rand"
func RollUint16() uint32 {
return uint32( uint16(rand.Intn(65536)))
}
type UdpConn struct {
conn *net.UDPConn
buffer *bytes.Buffer
vc *VideoChat
}
func NewUdpConn(conn *net.UDPConn) *UdpConn {
return &UdpConn{conn, new(bytes.Buffer),&VideoChat{sn: uint32(RollUint16())}}
}
func (uh *UdpConn) ReadFrom(b []byte) ( int, net.Addr, error) {
data := make([]byte,1024*10)
n,addr,err:=uh.conn.ReadFrom(data);
if err!=nil || n==0 {
return n,addr,err
}
//b=data[uh.vc.Size():n];
_n:=copy(b,data[uh.vc.Size():n]);
return _n,addr,err;
}
// Serialize implements PacketHeader.
func (uh *UdpConn) WriteTo(p []byte, addr net.Addr) (int, error) {
var header []byte = make([]byte, uh.vc.Size())
uh.vc.Serialize(header)
uh.buffer.Reset()
uh.buffer.Write(header)
uh.buffer.Write(p)
n, err := uh.conn.WriteTo(uh.buffer.Bytes(), addr)
if err != nil {
return n, err
}
return len(p),err;
}
func (c *UdpConn) Close() error {
return c.conn.Close()
}
func (c *UdpConn) LocalAddr() net.Addr {
return c.conn.LocalAddr()
}
func (c *UdpConn) Write(b []byte) (int, error) {
var header []byte = make([]byte, c.vc.Size())
c.vc.Serialize(header)
c.buffer.Reset()
c.buffer.Write(header)
c.buffer.Write(b)
return c.conn.Write(c.buffer.Bytes())
}
func (c *UdpConn) SetDeadline(t time.Time) error {
return c.conn.SetDeadline(t)
}
func (c *UdpConn) SetReadBuffer(bytes int) error{
return c.conn.SetReadBuffer(bytes)
}
func (c *UdpConn) SyscallConn() (syscall.RawConn, error) {
return c.conn.SyscallConn()
}
func (c *UdpConn) SetReadDeadline(t time.Time) error {
return c.conn.SetReadDeadline(t)
}
func (c *UdpConn) SetWriteDeadline(t time.Time) error {
return c.conn.SetWriteDeadline(t)
}