tspool

package module
Version: v0.0.0-...-92bc4a5 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2018 License: MIT Imports: 4 Imported by: 0

README

tspool

A TCP Library use worker pool to improve performance and protect your server.

Build Status Code Coverage License GoDoc

Install

go get github.com/two/tspool

Usage

Build your server with tspool

server
package main

import (
	"github.com/two/tspool"
	"log"
	"net"
)

func main() {
	wp, err := tspool.DefaultWorkerPool(100, 200)
	if err != nil {
		log.Fatalln(err)
	}
	server := &tspool.Server{
		Addr:          "0.0.0.0:8088",
		Handler:       handler,
		ErrHandler:    errHandler,
		WorkerPool:    wp,
		RejectHandler: rejectHandler,
	}
	err = tspool.ListenAndServe(server)
	if err != nil {
		log.Fatalln(err)
	}
}

func handler(c net.Conn) {
	addr := c.RemoteAddr()
	c.Write([]byte("hello"))
	c.Close()
	log.Println(addr.String())
}

func errHandler(c net.Conn, err string) {
	defer c.Close()
	log.Fatalln("run server error: " + err)
}

func rejectHandler(c net.Conn, err string) {
	defer c.Close()
	log.Println("reject connect error: " + err)
}

Build your tspool client


package main

import (
	"log"
	"net"
	"sync"
	"time"
)

var wg = new(sync.WaitGroup)

func main() {
	var num int = 2000
	wg.Add(num)
	for i := 0; i < num; i++ {
		go conn()
	}
	wg.Wait()
	log.Println("done")
}
func conn() {
	defer wg.Done()
	addr := "0.0.0.0:8088"
	d := net.Dialer{Timeout: 100 * time.Millisecond}
	conn, err := d.Dial("tcp", addr)
	if err != nil {
		log.Fatalln(err)
	}
	defer conn.Close()
	raddr := conn.LocalAddr()
	var r = make([]byte, 1024)
	_, err = conn.Read(r)
	if err != nil {
		log.Printf(raddr.String() + " read error: " + err.Error())
	}
	log.Printf(raddr.String() + " got " + string(r))
}

Define your own worker pool and worker

Example

example

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ListenAndServe

func ListenAndServe(srv *Server) error

ListenAndServe will listen the port and serve your request

Types

type Server

type Server struct {
	Addr          string
	WorkerPool    WorkerPool
	Handler       func(net.Conn)
	ErrHandler    func(net.Conn, string)
	RejectHandler func(net.Conn, string)
}

Server have all functions that you should define to deal connect

type Worker

type Worker interface {
	Work(*Server, net.Conn)
}

Worker deal the request

type WorkerPool

type WorkerPool interface {
	Get() (Worker, error)
	Put(Worker) error
}

WorkerPool provide Get and Put functions of pool

func DefaultWorkerPool

func DefaultWorkerPool(cap ...uint) (WorkerPool, error)

DefaultWorkerPool return the default config of pool

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto