forked from netbrain/goautosocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
doc.go
64 lines (51 loc) · 1.98 KB
/
doc.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
// Copyright © 2015 Clement 'cmc' Rey <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
/*
The GAS library provides auto-reconnecting TCP sockets in a
tiny, fully tested, thread-safe API.
The `TCPClient` struct embeds a `net.TCPConn` and overrides
its `Read()` and `Write()` methods, making it entirely compatible
with the `net.Conn` interface and the rest of the `net` package.
This means you should be able to use this library by just
replacing `net.Dial` with `gas.Dial` in your code.
GAS uses the `atomic` package to synchronize reconnections between
multiple goroutines; it doesn't add any extra locking upon the
standard `net.TCPConn` API, except to protect its configuration from races.
Hence, you should always use the `TCPClient.Set*` methods *before* you
actually start doing any I/O.
To test the library, you can run a local TCP server with:
$ ncat -l 9999 -k
and run this code:
package main
import (
"log"
"time"
"github.com/teh-cmc/goautosocket"
)
func main() {
// connect to a TCP server
conn, err := gas.Dial("tcp", "localhost:9999")
if err != nil {
log.Fatal(err)
}
// client sends "hello, world!" to the server every second
for {
_, err := conn.Write([]byte("hello, world!\n"))
if err != nil {
// if the client reached its retry limit, give up
if err == gas.ErrMaxRetries {
log.Println("client gave up, reached retry limit")
return
}
// not a GAS error, just panic
log.Fatal(err)
}
log.Println("client says hello!")
time.Sleep(time.Second)
}
}
Then try to kill and reboot your server, the client will automatically reconnect and start sending messages again; unless it has reached its retry limit.
*/
package gas