This repository has been archived by the owner on Feb 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapper.go
97 lines (86 loc) · 2.06 KB
/
wrapper.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
91
92
93
94
95
96
97
// Package dgtcp provides a simple implementation of
// TCP-based datagram-style protocol.
// It overrides Read() and Write(). It can send and receive not larger
// than 65536 bytes per packet.
//
// Read() and Write() are coroutine-safe.
//
// DGTCP Protocol:
// [ packet #1 ] [ packet #2 ] ...
// <len> < data > <len> < data > ...
// 01 FF 00 01 02 ...(0x1FF bytes) 00 03 23 12 AB ...
package dgtcp
import (
"errors"
"net"
"sync"
)
// DGTCPConn is the instance of DGTCP connection.
// It has all methods of *net.TCPConn.
type DGTCPConn struct {
*net.TCPConn
readLen int
wl, rl sync.Locker
}
// ErrOverflow will be reported if your buffer is not big enough to receive(read),
// or your buffer is too big to send(write).
var ErrOverflow = errors.New("packet is too large to receive or send")
func (c *DGTCPConn) fillBuf(buf []byte) error {
var pos int
for pos != len(buf) {
size, err := c.TCPConn.Read(buf[pos:])
if err != nil {
return err
}
pos += size
}
return nil
}
// Read receives one packet and put it into buf.
func (c *DGTCPConn) Read(buf []byte) (int, error) {
c.rl.Lock()
defer c.rl.Unlock()
var plen [2]byte
var ilen int
if c.readLen == 0 {
err := c.fillBuf(plen[:])
if err != nil {
return 0, err
}
ilen = int(plen[0])<<8 + int(plen[1])
} else {
ilen = c.readLen
}
if ilen > len(buf) {
c.readLen = ilen
return 0, ErrOverflow
}
err := c.fillBuf(buf[:ilen])
c.readLen = 0
return ilen, err
}
// Write sends one packet.
func (c *DGTCPConn) Write(buf []byte) error {
c.wl.Lock()
defer c.wl.Unlock()
var ilen = len(buf)
if ilen > 65536 {
return ErrOverflow
}
var plen [2]byte
plen[0] = byte((ilen & 0xff00) >> 8)
plen[1] = byte(ilen & 0xff)
_, err := c.TCPConn.Write(plen[:])
if err != nil {
return err
}
_, err = c.TCPConn.Write(buf)
return err
}
// New returns an instance of DGTCPConn. c must be a pointer of net.TCPConn.
func New(c net.Conn) *DGTCPConn {
if tcp, ok := c.(*net.TCPConn); ok {
return &DGTCPConn{tcp, 0, new(sync.Mutex), new(sync.Mutex)}
}
return nil
}