File: conn.go

package info (click to toggle)
golang-github-siddontang-go 0.0~git20170517.0.cb568a3-4
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 484 kB
  • sloc: makefile: 3
file content (78 lines) | stat: -rw-r--r-- 1,235 bytes parent folder | download | duplicates (2)
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
package rpc

import (
	"encoding/binary"
	"fmt"
	"io"
	"net"
)

type conn struct {
	co net.Conn
}

func newConn(network, addr string) (*conn, error) {
	c, err := net.Dial(network, addr)
	if err != nil {
		return nil, err
	}

	co := new(conn)
	co.co = c
	return co, nil
}

func (c *conn) Close() error {
	return c.co.Close()
}

func (c *conn) Call(data []byte) ([]byte, error) {
	if err := c.WriteMessage(data); err != nil {
		return nil, err
	}

	if buf, err := c.ReadMessage(); err != nil {
		return nil, err
	} else {
		return buf, nil
	}
}

func (c *conn) WriteMessage(data []byte) error {
	buf := make([]byte, 4+len(data))

	binary.LittleEndian.PutUint32(buf[0:4], uint32(len(data)))

	copy(buf[4:], data)

	n, err := c.co.Write(buf)
	if err != nil {
		c.Close()
		return err
	} else if n != len(buf) {
		c.Close()
		return fmt.Errorf("write %d less than %d", n, len(buf))
	}
	return nil
}

func (c *conn) ReadMessage() ([]byte, error) {
	l := make([]byte, 4)

	_, err := io.ReadFull(c.co, l)
	if err != nil {
		c.Close()
		return nil, err
	}

	length := binary.LittleEndian.Uint32(l)

	data := make([]byte, length)
	_, err = io.ReadFull(c.co, data)
	if err != nil {
		c.Close()
		return nil, err
	} else {
		return data, nil
	}
}