打算闲的时候写一个tcp_pool.刚开始,慢慢完善

来源:转载

package mainimport ( "errors" "fmt" "net" "sync" "time")type IPPool struct { IP []string Maxconn int TimeOut int64}type ConnectionPool struct { IPPool Lock *sync.RWMutex Connection map[string]chan net.Conn UseConnection map[string]chan net.Conn}func (this *ConnectionPool) GetConnection(ip string) { }func (this *ConnectionPool) Alive(contain string) {}func (this *ConnectionPool) New(ip string) { if this.Index(ip) { if _, ok := this.Connection[ip]; !ok { ConChan := make(chan net.Conn, this.Maxconn) err := createConList(ip, ConChan, this.TimeOut) if err != nil { return err } this.Lock.Lock() this.Connection[ip] = ConChan this.Lock.Unlock() } return errors.New(fmt.Sprintf("%s: Already exists."), ip) } ConChan := make(chan net.Conn, this.Maxconn) err := createConList(ip, ConChan, this.TimeOut) if err != nil { return err } if !this.Index(ip) { this.Lock.Lock() this.IP = append(this.IP, ip) this.Connection[ip] = ConChan this.Lock.Unlock() return nil } return errors.New(fmt.Sprintf("%s: Already exists."), ip)}func (this *ConnectionPool) Index(ip string) bool { this.Lock.RLock() defer this.Lock.RUnlock() for _, v := range this.IP { if v == ip { return true } } return false}func (this *IPPool) Init() *ConnectionPool { M := ConnectionPool{Lock: new(sync.RWMutex), Connection: make(map[string]chan net.Conn), UseConnection: make(map[string]chan net.Conn)} for _, addr := range this.IP { ConChan := make(chan net.Conn, this.Maxconn) err := createConList(addr, ConChan, this.TimeOut) if err != nil { continue } M.Connection[addr] = ConChan } M.IP = this.IP M.TimeOut = this.TimeOut M.Maxconn = this.Maxconn M.UseConnection = make(chan net.Conn, this.Maxconn) return &M}func createConList(ip string, ConChan chan net.Conn, t int64) error { for i := 0; i < cap(ConChan); i++ { con, err := dial(ip, t) if err != nil { fmt.Println(err) continue } ConChan <- con } if len(ConChan) <= 0 { return errors.New(fmt.Sprintf("%s: can't connection."), ip) } return nil}func dial(ip string, t int64) (net.Conn, error) { if _, err := net.ResolveTCPAddr("tcp", ip); err != nil { return nil, err } return net.DialTimeout("tcp", ip, time.Second*time.Duration(t))}



分享给朋友:
您可能感兴趣的文章:
随机阅读: