-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpast_connection.go
61 lines (53 loc) · 1.27 KB
/
past_connection.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
package main
import (
"github.com/google/uuid"
"net"
"sync"
)
type PasteConnection struct {
conn net.Conn
id string
}
func NewPasteConnection(conn net.Conn) *PasteConnection {
return &PasteConnection{
conn: conn,
id: conn.RemoteAddr().String() + "-" + uuid.New().String()[:5],
}
}
func (receiver *PasteConnection) Send(content []byte) {
contentLen := len(content)
_, err := receiver.conn.Write(Int64ToBytes(int64(contentLen)))
if err != nil {
return
}
_, err = receiver.conn.Write(content)
if err != nil {
return
}
}
func (receiver *PasteConnection) Read() ([]byte, error) {
contentLenInfo := make([]byte, headerLen)
_, err := receiver.conn.Read(contentLenInfo)
if err != nil {
return nil, err
}
contentLen := BytesToInt64(contentLenInfo)
content := make([]byte, contentLen)
_, err = receiver.conn.Read(content)
if err != nil {
return nil, nil
}
return content, nil
}
type PasteConnectionList struct {
connList map[string]*PasteConnection
lock sync.Mutex
}
var pasteConnectionList PasteConnectionList = PasteConnectionList{
connList: make(map[string]*PasteConnection),
}
func (receiver *PasteConnectionList) add(connection *PasteConnection) {
receiver.lock.Lock()
receiver.connList[connection.id] = connection
defer receiver.lock.Unlock()
}