发布基础组件包-KISS(日常用作游戏服务器开发,但不限于游戏服务器开发)

nothollyhigh · · 3355 次点击
更多评论
### tcp echo server ```golang package main import ( "github.com/nothollyhigh/kiss/log" "github.com/nothollyhigh/kiss/net" "time" ) var () const ( addr = ":8888" CMD_ECHO = uint32(1) ) func onEcho(client *net.TcpClient, msg net.IMessage) { log.Info("tcp server onEcho from %v: %v", client.Conn.RemoteAddr().String(), string(msg.Body())) client.SendMsg(msg) } func main() { server := net.NewTcpServer("Echo") // 初始化协议号 server.Handle(CMD_ECHO, onEcho) server.Serve(addr, time.Second*5) } ``` ### tcp echo client ```golang package main import ( "fmt" "github.com/nothollyhigh/kiss/log" "github.com/nothollyhigh/kiss/net" "time" ) var ( addr = "127.0.0.1:8888" CMD_ECHO = uint32(1) ) func onConnected(c *net.TcpClient) { log.Info("TcpClient OnConnected") } func onEcho(client *net.TcpClient, msg net.IMessage) { log.Debug("tcp client onEcho from %v: %v", client.Conn.RemoteAddr().String(), string(msg.Body())) } func main() { autoReconn := true netengine := net.NewTcpEngine() // 初始化协议号 netengine.Handle(CMD_ECHO, onEcho) client, err := net.NewTcpClient(addr, netengine, nil, autoReconn, onConnected) if err != nil { log.Panic("NewTcpClient failed: %v, %v", client, err) } for i := 0; true; i++ { err = client.SendMsg(net.NewMessage(CMD_ECHO, []byte(fmt.Sprintf("hello %v", i)))) if err != nil { log.Error("tcp client echo failed: %v", err) } time.Sleep(time.Second) } } ```
#1
### websocket echo server ```golang package main import ( "github.com/nothollyhigh/kiss/log" "github.com/nothollyhigh/kiss/net" ) var ( addr = ":8888" CMD_ECHO = uint32(1) ) func onEcho(client *net.WSClient, msg net.IMessage) { log.Info("ws server onEcho from %v: %v", client.Conn.RemoteAddr().String(), string(msg.Body())) client.SendMsg(msg) } func main() { server, err := net.NewWebsocketServer("echo", addr) if err != nil { log.Panic("NewWebsocketServer failed: %v", err) } // 初始化http ws路由 server.HandleWs("/ws/echo") // 初始化协议号 server.Handle(CMD_ECHO, onEcho) server.Serve() } ``` ### websocket echo client ```golang package main import ( "fmt" "github.com/nothollyhigh/kiss/log" "github.com/nothollyhigh/kiss/net" "time" ) var ( addr = "ws://localhost:8888/ws/echo" CMD_ECHO = uint32(1) ) func onEcho(client *net.WSClient, msg net.IMessage) { log.Debug("ws client onEcho from %v: %v", client.Conn.RemoteAddr().String(), string(msg.Body())) } func main() { client, err := net.NewWebsocketClient(addr) if err != nil { log.Panic("NewWebsocketClient failed: %v, %v", err, time.Now()) } // 初始化协议号 client.Handle(CMD_ECHO, onEcho) for i := 0; true; i++ { err = client.SendMsg(net.NewMessage(CMD_ECHO, []byte(fmt.Sprintf("hello %v", i)))) if err != nil { log.Error("ws client echo failed: %v", err) break } time.Sleep(time.Second) } } ```
#2