gas

package module
v0.0.0-...-bef85f0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 24, 2015 License: MIT Imports: 5 Imported by: 2

README

GoAutoSocket (GAS) Status Build Status GoDoc

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.

Install

get -u github.com/teh-cmc/goautosocket

Usage

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.

Examples

An advanced example of a client writing to a buggy server that's randomly crashing and rebooting:

package main

import (
    "log"
    "math/rand"
    "net"
    "sync"
    "time"

    "github.com/teh-cmc/goautosocket"
)

func main() {
    rand.Seed(time.Now().UnixNano())

    // open a server socket
    s, err := net.Listen("tcp", "localhost:0")
    if err != nil {
        log.Fatal(err)
    }
    // save the original port
    addr := s.Addr()

    // connect a client to the server
    c, err := gas.Dial("tcp", s.Addr().String())
    if err != nil {
        log.Fatal(err)
    }
    defer c.Close()

    // shut down and boot up the server randomly
    var swg sync.WaitGroup
    swg.Add(1)
    go func() {
        defer swg.Done()
        for i := 0; i < 5; i++ {
            log.Println("server up")
            time.Sleep(time.Millisecond * 100 * time.Duration(rand.Intn(20)))
            if err := s.Close(); err != nil {
                log.Fatal(err)
            }
            log.Println("server down")
            time.Sleep(time.Millisecond * 100 * time.Duration(rand.Intn(20)))
            s, err = net.Listen("tcp", addr.String())
            if err != nil {
                log.Fatal(err)
            }
        }
    }()

    // client writes to the server and reconnects when it has to
    // this is the interesting part
    var cwg sync.WaitGroup
    cwg.Add(1)
    go func() {
        defer cwg.Done()
        for {
            if _, err := c.Write([]byte("hello, world!\n")); err != nil {
                switch e := err.(type) {
                case gas.Error:
                    if e == gas.ErrMaxRetries {
                        log.Println("client leaving, reached retry limit")
                        return
                    }
                default:
                    log.Fatal(err)
                }
            }
            log.Println("client says hello!")
        }
    }()

    // terminates the server indefinitely
    swg.Wait()
    if err := s.Close(); err != nil {
        log.Fatal(err)
    }

    // wait for the client to give up
    cwg.Wait()
}

You can also find an example with concurrency here.

Disclaimer

This was built with my needs in mind, no more, no less. That is, I needed a simple, tested and thread-safe API to handle a situation in which I have:

  • on one end, a lot of goroutines concurrently writing to a TCP socket
  • on the other end, a TCP server that I have no control over (hence the main reason why UDP is out of the question) and which might be rebooted at anytime I also needed the ability to give up on sending a message after an abritrary amount of tries/time (i.e., ERR_MAX_TRIES). Pretty straightforward stuff.

Basically, my use case is this situation.

Surprisingly, I couldn't find such a library (I guess I either didn't look in the right place, or just not hard enough..? oh well); so here it is. Do not hesitate to send a pull request if this doesn't cover all your needs (and it probably won't), they are more than welcome.

If you're looking for some more insight, you might also want to look at this discussion we had on reddit.

License License

The MIT License (MIT) - see LICENSE for more details

Copyright (c) 2015 Clement 'cmc' Rey cr.rey.clement@gmail.com

Documentation

Overview

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.

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.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Dial

func Dial(network, addr string) (net.Conn, error)

Dial returns a new net.Conn.

The new client connects to the remote address `raddr` on the network `network`, which must be "tcp", "tcp4", or "tcp6".

This complements net package's Dial function.

Types

type Error

type Error int

Error is the error type of the GAS package.

It implements the error interface.

const (
	// ErrMaxRetries is returned when the called function failed after the
	// maximum number of allowed tries.
	ErrMaxRetries Error = 0x01
)

func (Error) Error

func (e Error) Error() string

Error returns the error as a string.

type TCPClient

type TCPClient struct {
	*net.TCPConn
	// contains filtered or unexported fields
}

TCPClient provides a TCP connection with auto-reconnect capabilities.

It embeds a *net.TCPConn and thus implements the net.Conn interface.

Use the SetMaxRetries() and SetRetryInterval() methods to configure retry values; otherwise they default to maxRetries=5 and retryInterval=100ms.

TCPClient can be safely used from multiple goroutines.

Example
// open a server socket
s, err := net.Listen("tcp", "localhost:0")
if err != nil {
	log.Fatal(err)
}
// save the original port
addr := s.Addr()

// connect a client to the server
c, err := Dial("tcp", s.Addr().String())
if err != nil {
	log.Fatal(err)
}
defer c.Close()

// shut down and boot up the server randomly
var swg sync.WaitGroup
swg.Add(1)
go func() {
	defer swg.Done()
	for i := 0; i < 5; i++ {
		log.Println("server up")
		time.Sleep(time.Millisecond * 100 * time.Duration(rand.Intn(20)))
		if err := s.Close(); err != nil {
			log.Fatal(err)
		}
		log.Println("server down")
		time.Sleep(time.Millisecond * 100 * time.Duration(rand.Intn(20)))
		s, err = net.Listen("tcp", addr.String())
		if err != nil {
			log.Fatal(err)
		}
	}
}()

// client writes to the server and reconnects when it has to
// this is the interesting part
var cwg sync.WaitGroup
cwg.Add(1)
go func() {
	defer cwg.Done()
	for {
		if _, err := c.Write([]byte("hello, world!\n")); err != nil {
			switch e := err.(type) {
			case Error:
				if e == ErrMaxRetries {
					log.Println("client leaving, reached retry limit")
					return
				}
			default:
				log.Fatal(err)
			}
		}
	}
}()

// terminates the server indefinitely
swg.Wait()
if err := s.Close(); err != nil {
	log.Fatal(err)
}

// wait for the client to give up
cwg.Wait()
Output:

func DialTCP

func DialTCP(network string, laddr, raddr *net.TCPAddr) (*TCPClient, error)

DialTCP returns a new *TCPClient.

The new client connects to the remote address `raddr` on the network `network`, which must be "tcp", "tcp4", or "tcp6". If `laddr` is not nil, it is used as the local address for the connection.

This overrides net.TCPConn's DialTCP function.

func (*TCPClient) GetMaxRetries

func (c *TCPClient) GetMaxRetries() int

GetMaxRetries gets the retry limit for the TCPClient.

Assuming i is the current retry iteration, the total sleep time is t = retryInterval * (2^i)

func (*TCPClient) GetRetryInterval

func (c *TCPClient) GetRetryInterval() time.Duration

GetRetryInterval gets the retry interval for the TCPClient.

Assuming i is the current retry iteration, the total sleep time is t = retryInterval * (2^i)

func (*TCPClient) Read

func (c *TCPClient) Read(b []byte) (int, error)

Read wraps net.TCPConn's Read method with reconnect capabilities.

It will return ErrMaxRetries if the retry limit is reached.

func (*TCPClient) ReadFrom

func (c *TCPClient) ReadFrom(r io.Reader) (int64, error)

ReadFrom wraps net.TCPConn's ReadFrom method with reconnect capabilities.

It will return ErrMaxRetries if the retry limit is reached.

func (*TCPClient) SetMaxRetries

func (c *TCPClient) SetMaxRetries(maxRetries int)

SetMaxRetries sets the retry limit for the TCPClient.

Assuming i is the current retry iteration, the total sleep time is t = retryInterval * (2^i)

This function completely Lock()s the TCPClient.

func (*TCPClient) SetRetryInterval

func (c *TCPClient) SetRetryInterval(retryInterval time.Duration)

SetRetryInterval sets the retry interval for the TCPClient.

Assuming i is the current retry iteration, the total sleep time is t = retryInterval * (2^i)

This function completely Lock()s the TCPClient.

func (*TCPClient) Write

func (c *TCPClient) Write(b []byte) (int, error)

Write wraps net.TCPConn's Write method with reconnect capabilities.

It will return ErrMaxRetries if the retry limit is reached.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL