-
Notifications
You must be signed in to change notification settings - Fork 633
/
connection.go
89 lines (78 loc) 路 1.95 KB
/
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
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
package gowandb
import (
"bufio"
"context"
"encoding/binary"
"fmt"
"github.com/wandb/wandb/nexus/pkg/server"
"github.com/wandb/wandb/nexus/pkg/service"
"net"
"google.golang.org/protobuf/proto"
)
// Connection is a connection to the server.
type Connection struct {
// ctx is the context for the run
ctx context.Context
// Conn is the connection to the server
net.Conn
Mbox *Mailbox
}
// NewConnection creates a new connection to the server.
func NewConnection(ctx context.Context, addr string) (*Connection, error) {
conn, err := net.Dial("tcp", addr)
if err != nil {
err = fmt.Errorf("error connecting to server: %w", err)
return nil, err
}
mbox := NewMailbox()
connection := &Connection{
ctx: ctx,
Conn: conn,
Mbox: mbox,
}
return connection, nil
}
// Send sends a message to the server.
func (c *Connection) Send(msg proto.Message) error {
data, err := proto.Marshal(msg)
if err != nil {
return fmt.Errorf("error marshaling message: %w", err)
}
writer := bufio.NewWriterSize(c, 16384)
header := server.Header{Magic: byte('W'), DataLength: uint32(len(data))}
err = binary.Write(writer, binary.LittleEndian, &header)
if err != nil {
return fmt.Errorf("error writing header: %w", err)
}
if _, err = writer.Write(data); err != nil {
return fmt.Errorf("error writing message: %w", err)
}
if err = writer.Flush(); err != nil {
return fmt.Errorf("error flushing writer: %w", err)
}
return nil
}
func (c *Connection) Recv() {
scanner := bufio.NewScanner(c.Conn)
tokenizer := &server.Tokenizer{}
scanner.Split(tokenizer.Split)
for scanner.Scan() {
msg := &service.ServerResponse{}
err := proto.Unmarshal(scanner.Bytes(), msg)
if err != nil {
panic(err)
}
switch x := msg.ServerResponseType.(type) {
case *service.ServerResponse_ResultCommunicate:
c.Mbox.Respond(x.ResultCommunicate)
default:
}
}
}
// Close closes the connection.
func (c *Connection) Close() {
err := c.Conn.Close()
if err != nil {
return
}
}