3.5 使用Zinx-V0.3完成应用程序
接下来我们在基于Zinx写服务器,就可以配置一个简单的路由功能了。
A) 测试基于Zinx完成的服务端应用
Server.go
package main
import (
"fmt"
"zinx/ziface"
"zinx/znet"
)
//ping test 自定义路由
type PingRouter struct {
znet.BaseRouter //一定要先基础BaseRouter
}
//Test PreHandle
func (this *PingRouter) PreHandle(request ziface.IRequest) {
fmt.Println("Call Router PreHandle")
_, err := request.GetConnection().GetTCPConnection().Write([]byte("before ping ....\n"))
if err !=nil {
fmt.Println("call back ping ping ping error")
}
}
//Test Handle
func (this *PingRouter) Handle(request ziface.IRequest) {
fmt.Println("Call PingRouter Handle")
_, err := request.GetConnection().GetTCPConnection().Write([]byte("ping...ping...ping\n"))
if err !=nil {
fmt.Println("call back ping ping ping error")
}
}
//Test PostHandle
func (this *PingRouter) PostHandle(request ziface.IRequest) {
fmt.Println("Call Router PostHandle")
_, err := request.GetConnection().GetTCPConnection().Write([]byte("After ping .....\n"))
if err !=nil {
fmt.Println("call back ping ping ping error")
}
}
func main(){
//创建一个server句柄
s := znet.NewServer("[zinx V0.3]")
s.AddRouter(&PingRouter{})
//2 开启服务
s.Serve()
}
我们这里自定义了一个类似Ping操作的路由,就是当客户端发送数据,我们的处理业务就是返回给客户端"ping...ping..ping..", 为了测试,当前路由也同时实现了PreHandle和PostHandle两个方法。实际上Zinx会利用模板的设计模式,依次在框架中调用PreHandle
、Handle
、PostHandle
三个方法。
B) 启动Server.go
go run Server.go
C) 客户端应用测试程序
和之前的Client.go一样 没有改变
package main
import (
"fmt"
"net"
"time"
)
/*
模拟客户端
*/
func main() {
fmt.Println("Client Test ... start")
//3秒之后发起测试请求,给服务端开启服务的机会
time.Sleep(3 * time.Second)
conn,err := net.Dial("tcp", "127.0.0.1:7777")
if err != nil {
fmt.Println("client start err, exit!")
return
}
for {
_, err := conn.Write([]byte("Zinx V0.3"))
if err !=nil {
fmt.Println("write error err ", err)
return
}
buf :=make([]byte, 512)
cnt, err := conn.Read(buf)
if err != nil {
fmt.Println("read buf error ")
return
}
fmt.Printf(" server call back : %s, cnt = %d\n", buf, cnt)
time.Sleep(1*time.Second)
}
}
D) 启动Client.go
go run Client.go
运行结果如下:
服务端:
$ go run Server.go
Add Router succ!
[START] Server listenner at IP: 0.0.0.0, Port 7777, is starting
start Zinx server [zinx V0.3] succ, now listenning...
Reader Goroutine is running
Call Router PreHandle
Call PingRouter Handle
Call Router PostHandle
Call Router PreHandle
Call PingRouter Handle
Call Router PostHandle
Call Router PreHandle
Call PingRouter Handle
Call Router PostHandle
Call Router PreHandle
Call PingRouter Handle
Call Router PostHandle
Call Router PreHandle
Call PingRouter Handle
Call Router PostHandle
...
客户端:
$ go run Client.go
Client Test ... start
server call back : before ping ....
, cnt = 17
server call back : ping...ping...ping
After ping .....
, cnt = 36
server call back : before ping ....
ping...ping...ping
After ping .....
, cnt = 53
server call back : before ping ....
ping...ping...ping
After ping .....
, cnt = 53
server call back : before ping ....
ping...ping...ping
After ping .....
, cnt = 53
...
现在Zinx框架已经有路由功能了,虽然说目前只能配置一个,不过不要着急,很快我们会增加配置多路由的能力。