mq/app/http/tcppool/single.go

103 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tcppool
import (
"fmt"
"net"
"quenue/app/utils"
"quenue/config"
"sync"
"sync/atomic"
"time"
)
var (
full int32 = 0
TcpFactory = TcpHelper{Full: &full}
lockSingle sync.Once
)
type TcpHelper struct {
client net.Conn
lastTime int64
Full *int32
}
func (t *TcpHelper) Init(port string) *TcpHelper {
lockSingle.Do(func() {
var conn, err = net.DialTimeout("tcp", config.GetConf().Url+":"+port, 10*time.Second)
if err == nil {
t.client = conn
t.watch(t.client)
} else {
utils.Log(nil, config.GetConf().Url+":"+port)
}
})
return t
}
func (t *TcpHelper) reconnect(port string) {
var conn, err = net.Dial("tcp", "192.168.110.50:"+port)
if err == nil {
atomic.StoreInt32(t.Full, 0)
t.client = conn
t.watch(t.client)
}
}
func (t *TcpHelper) SendMsg(msg []byte) error {
msg = append(msg, '\n')
_, err := t.Init(config.GetConf().OrderPort).client.Write(msg)
var buffer [1]byte
// 持续读取数据
n, err := t.client.Read(buffer[:])
if err == nil {
if n > 0 {
recvStr := string(buffer[:n])
fmt.Println("结果recvStr:", recvStr)
if recvStr == "1" {
fmt.Println("客户端繁忙")
atomic.StoreInt32(t.Full, 1)
} else if recvStr == "2" {
fmt.Println("客户端空闲")
atomic.StoreInt32(t.Full, 0)
}
}
}
return err
}
func (t *TcpHelper) Close(conn net.Conn) {
t.client.Close()
}
func (t *TcpHelper) watch(conn net.Conn) {
go func() {
for {
fmt.Println("watch")
conn.SetWriteDeadline(time.Now().Add(time.Second * 15))
_, err := conn.Write([]byte("1"))
if err != nil {
utils.Log(nil, "连接关闭", err)
t.client.Close()
t.reconnect(config.GetConf().OrderPort)
return
} else {
var buffer [1]byte
// 持续读取数据
n, err := t.client.Read(buffer[:])
if err == nil && n > 0 {
recvStr := string(buffer[:n])
fmt.Println("结果recvStr:", recvStr)
if recvStr == "1" {
fmt.Println("客户端繁忙")
atomic.StoreInt32(t.Full, 1)
} else if recvStr == "2" {
fmt.Println("客户端空闲")
atomic.StoreInt32(t.Full, 0)
}
}
}
}
}()
}