package mainimport ( "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 []bytefunc 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]int64var 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.Poolfunc 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.Mutexfunc 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.Poolfunc 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)}总结
以上是内存溢出为你收集整理的没事随便写个小东西,虽然不知道想做啥,先留着全部内容,希望文章能够帮你解决没事随便写个小东西,虽然不知道想做啥,先留着所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)