前端之家收集整理的这篇文章主要介绍了
没事随便写个小东西,虽然不知道想做啥,先留着,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
import (
"bufio"
"encoding/json"
"fmt"
"net"
"strings"
"sync"
"time"
)
func smain() {
con,err := net.Dial("tcp","127.0.0.1:1789")
if err != nil {
fmt.Println(err)
return
}
var x Msg = Msg{Action: "script",Address: "http://127.0.0.1"}
b,_:=json.Marshal(x)
con.Write(b)
fmt.Fprint(con,"\r\n")
buf := make([]byte,100)
n,_ := con.Read(buf)
json.Unmarshal(buf[:n],&x)
fmt.Println(x)
fmt.Println(string(buf[:n]))
}
func main() {
lis,err := net.Listen("tcp","0.0.0.0:1789")
if err != nil {
fmt.Println(err)
return
}
defer lis.Close()
for {
con,err := lis.Accept()
if err != nil {
fmt.Println(err)
continue
}
go Hander(con)
}
}
type Msg struct {
Action string `json:action`
Address string `json:address`
JobID int64 `json:jobid`
Remark string `json:remark`
}
var empty []byte
func Hander(con net.Conn) {
defer con.Close()
ip := strings.Split(con.RemoteAddr().String(),":")[0]
if !statusMap.Add(ip) {
fmt.Fprint(con,"Already exist\r\n")
return
}
buf := getBufPool(con)
defer putBufPool(buf)
for {
line,_,err := buf.ReadLine()
if err != nil {
break
}
msg,err := decode(line)
if err != nil {
fmt.Fprint(con,"Unknow type\r\n")
putJsonPool(msg)
continue
}
if b,err := handlerMsg(msg); err != nil {
fmt.Fprint(con,"Can't execute this job.")
putJsonPool(msg)
continue
} else {
con.Write(b)
}
putJsonPool(msg)
}
}
func handlerMsg(msg *Msg) ([]byte,error) {
msg.JobID = NewID()
b,err := encode(msg)
if err != nil {
return empty,err
}
//执行对应操作
return b,nil
}
func handmsg(b []byte,ip string) {
switch string(b) {
case "Test.Ping":
statusMap[ip] = getNow()
}
}
type statusM map[string]int64
var statusMap statusM = make(statusM)
func (statusM) Flush(ip string) {
statusMap[ip] = getNow()
}
func (statusM) Del(ip string) {
delete(statusMap,ip)
}
func (statusM) Add(ip string) bool {
_,ok := statusMap[ip]
if ok {
return false
}
statusMap.Flush(ip)
return true
}
var Pool sync.Pool
func getBufPool(con net.Conn) *bufio.Reader {
buf := Pool.Get()
b,ok := buf.(*bufio.Reader)
if ok {
b.Reset(con)
return b
}
return bufio.NewReader(con)
}
func putBufPool(b *bufio.Reader) {
b.Reset(nil)
Pool.Put(b)
}
var GlobalLock sync.Mutex
func NewID() int64 {
GlobalLock.Lock()
defer GlobalLock.Unlock()
time.Sleep(1e9)
return getNow()
}
func getNow() int64 {
return time.Now().Unix()
}
func decode(b []byte) (*Msg,error) {
fmt.Print(string(b))
j := getJsonPool()
err := json.Unmarshal(b,j)
if err != nil {
return nil,err
}
return j,nil
}
func encode(msg *Msg) ([]byte,error) {
return json.Marshal(*msg)
}
var JsonPool sync.Pool
func getJsonPool() *Msg {
buf := Pool.Get()
b,ok := buf.(*Msg)
if ok {
return b
}
return new(Msg)
}
func putJsonPool(m *Msg) {
m = nil
Pool.Put(m)
}
原文链接:https://www.f2er.com/go/189999.html