87 lines
1.8 KiB
Go
87 lines
1.8 KiB
Go
package utils
|
|
|
|
import (
|
|
"bufio"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
var (
|
|
workNum int32 = 0
|
|
workSingleNum = &workNum
|
|
maxNum = 2000
|
|
handNum int32 = 0
|
|
handSingleNum = &handNum
|
|
busy int32 = 0
|
|
busySingle = &busy
|
|
)
|
|
|
|
func handLogacal(conn net.Conn, data []byte) {
|
|
conn.Write([]byte("2\n"))
|
|
time.Sleep(1 * time.Second)
|
|
atomic.AddInt32(workSingleNum, -1)
|
|
atomic.AddInt32(handSingleNum, 1)
|
|
atomic.StoreInt32(busySingle, 0)
|
|
fmt.Println(*handSingleNum, "处理条数")
|
|
fmt.Println(string(data), "消息")
|
|
|
|
}
|
|
|
|
func handleConnection(conn net.Conn) {
|
|
for {
|
|
buf := make([]byte, 1024)
|
|
reader := bufio.NewReader(conn)
|
|
line, err := reader.ReadString('\n')
|
|
if err != nil {
|
|
fmt.Println("Error reading from connection:", err)
|
|
return
|
|
}
|
|
// 将读取到的字符串转换为字节切片
|
|
buf = []byte(line)
|
|
if err == nil && len(buf) > 2 {
|
|
if atomic.LoadInt32(workSingleNum) >= int32(maxNum) {
|
|
if atomic.LoadInt32(busySingle) == 0 {
|
|
fmt.Println("繁忙")
|
|
atomic.StoreInt32(busySingle, 1)
|
|
conn.Write([]byte("5\n"))
|
|
continue
|
|
}
|
|
|
|
} else {
|
|
var data map[string]interface{}
|
|
json.Unmarshal(buf, &data)
|
|
fmt.Println("收到", *workSingleNum, maxNum, string(buf))
|
|
conn.Write([]byte(data["serial_number"].(string) + "\n"))
|
|
go handLogacal(conn, buf)
|
|
atomic.AddInt32(workSingleNum, 1)
|
|
conn.Write([]byte("2\n"))
|
|
}
|
|
|
|
} else {
|
|
conn.Write([]byte("6\n"))
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
func StartTcpServer() {
|
|
listener, err := net.Listen("tcp", ":8080")
|
|
if err != nil {
|
|
fmt.Println("Error starting server:", err)
|
|
return
|
|
}
|
|
defer listener.Close()
|
|
|
|
for {
|
|
conn, err := listener.Accept()
|
|
if err != nil {
|
|
fmt.Println("Error accepting connection:", err)
|
|
continue
|
|
}
|
|
go handleConnection(conn)
|
|
}
|
|
}
|