github:https://github.com/by-zhang/s... 厚臉皮求stargit
import "stpro"
/** 三步搭建服務端 1 定義任意名稱struct的數據結構,必須包含Pmap、Phost兩個 字段,其中Phost爲服務端ip+port拼接的字符串,Pmap爲自定 義數據包類型與數據包名稱的映射。 2 實例化對象爲字段賦值,實現對應已定義`包名稱`的數據包處 理方法,方法名必爲"P[包名稱]",如type包的處理方法爲Ptype 。方法中請定義數據處理邏輯,輸入輸入皆爲[]byte類型。 3 stpro.New()傳入實例化的對象,如無報錯則服務端開始監聽, 並按照你所定義的邏輯處理數據包,返回響應數據。 **/ package main import ( "fmt" "stpro" ) type Server struct { Phost string Pmap map[uint8]string } func (m Server) Ptype(in []byte) (out []byte) { fmt.Printf("客戶端發來type包:%s\n", in) /** process... **/ bytes := []byte("hello1") return bytes } func (m Server) Pname(in []byte) (out []byte) { fmt.Printf("客戶端發來name包:%s\n", in) /** process... **/ bytes := []byte("hello2") return bytes } func main() { m := Model{ Phost: ":9091", Pmap: make(map[uint8]string), } m.Pmap[0x01] = "type" m.Pmap[0x02] = "name" err := stpro.New(m) if err != nil { fmt.Println(err) } }
/** 三部搭建客戶端 1 數據結構同服務端。 2 P[type]方法是發送對應包後接收到響應數據的處理方法。 3 實例化對象,並調用Send(type byte, content []byte)方 法發送數據到客戶端,接收到的數據後會自定按照上述定 義方法處理。 **/ package main import ( "fmt" "stpro" ) type Client struct { Phost string Pmap map[byte]string } func (c Client) Ptype(in []byte) { fmt.Printf("收到了type包的回覆:%s\n", in) } func (c Client) Pname(in []byte) { fmt.Printf("收到了name包的回覆:%s\n", in) } func main() { client, err := stpro.NewClient(Client{ Phost: "192.168.1.106:9091", Pmap: map[byte]string{ 0x01: "type", 0x02: "name", }, }) if err != nil { fmt.Println(err) return } err = client.Send(0x02, []byte("jintianzhenhao")) if err != nil { fmt.Println(err) return } err = client.Send(0x01, []byte("jintianzhenhao3333")) if err != nil { fmt.Println(err) return } }