forked from philippseith/signalr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
netconnection.go
54 lines (48 loc) · 1.15 KB
/
netconnection.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
package signalr
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"net"
"time"
)
type netConnection struct {
ConnectionBase
conn net.Conn
}
// NewNetConnection wraps net.Conn into a Connection
func NewNetConnection(ctx context.Context, conn net.Conn) Connection {
netConn := &netConnection{
ConnectionBase: *NewConnectionBase(ctx, getConnectionID()),
conn: conn,
}
go func() {
<-ctx.Done()
_ = conn.Close()
}()
return netConn
}
func (nc *netConnection) Write(p []byte) (n int, err error) {
n, err = ReadWriteWithContext(nc.Context(),
func() (int, error) { return nc.conn.Write(p) },
func() { _ = nc.conn.SetWriteDeadline(time.Now()) })
if err != nil {
err = fmt.Errorf("%T: %w", nc, err)
}
return n, err
}
func (nc *netConnection) Read(p []byte) (n int, err error) {
n, err = ReadWriteWithContext(nc.Context(),
func() (int, error) { return nc.conn.Read(p) },
func() { _ = nc.conn.SetReadDeadline(time.Now()) })
if err != nil {
err = fmt.Errorf("%T: %w", nc, err)
}
return n, err
}
func getConnectionID() string {
bytes := make([]byte, 16)
_, _ = rand.Read(bytes)
return base64.StdEncoding.EncodeToString(bytes)
}