-
Notifications
You must be signed in to change notification settings - Fork 2
/
conn.go
46 lines (40 loc) · 832 Bytes
/
conn.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
package tcp
import (
"bufio"
"bytes"
"context"
"io"
"net"
)
type conn struct {
addr string
rwc net.Conn
srv *Server
}
func (c *conn) bySegment(ctx context.Context, segment string, body io.Reader) {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
w := newWriter(c.rwc)
req := c.newRequest(segment, body).WithContext(ctx)
c.srv.ServeTCP(w, req)
}
func (c *conn) newRequest(segment string, body io.Reader) *Request {
req := NewRequest(segment, body)
req.RemoteAddr = c.addr
return req
}
func (c *conn) serve(ctx context.Context) {
// New connection
go c.bySegment(ctx, SYN, nil)
// Waiting for messages
r := bufio.NewReader(c.rwc)
for {
d, err := r.ReadBytes('\n')
if err != nil {
break
}
go c.bySegment(ctx, ACK, bytes.NewReader(d))
}
// Connection closed
c.bySegment(ctx, FIN, nil)
}