Skip to content

01 QuickStart

刘丹冰 edited this page May 11, 2023 · 2 revisions

Case source code https://github.com/aceld/zinx-usage/tree/main/quick_start

Download zinx Source

$go get github.com/aceld/zinx

Note: Zinx requires Golang version 1.16+

I. Zinx-Server

A server application developed based on the Zinx framework, the main function steps are relatively simple, requiring a maximum of only 3 steps.

  1. Create a server service instance.
  2. Configure custom routing and business logic.
  3. Start the service.
Package main
import "github.com/aceld/zinx/znet"

func main() {
    //1 Create a server service
    s := znet.NewServer()

    //2 Configure routing
    s.AddRouter(1, &PingRouter{})

    //3 Start the service
    s.Serve()
}

PingRouter is a custom router for handling messages with ID 0 received from the client. We can define a custom router as follows:

import (
    "fmt"
    "github.com/aceld/zinx/ziface"
)

// PingRouter MsgId=1 router
type PingRouter struct {
    znet.BaseRouter
}

//Ping Handle MsgId=1 router processing method
func (r *PingRouter) Handle(request ziface.IRequest) {
    //Read client data
    fmt.Println("recv from client : msgId=", request.GetMsgID(), ", data=", string(request.GetData()))
}

Handle() is the business processing function for messages with ID 0. Then we can start the server.

$ go run server.go

The following output indicates that the server has been started:

                                        
              ██                        
              ▀▀                        
 ████████   ████     ██▄████▄  ▀██  ██▀ 
     ▄█▀      ██     ██▀   ██    ████   
   ▄█▀        ██     ██    ██    ▄██▄   
 ▄██▄▄▄▄▄  ▄▄▄██▄▄▄  ██    ██   ▄█▀▀█▄  
 ▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀  ▀▀    ▀▀  ▀▀▀  ▀▀▀ 
                                        
┌──────────────────────────────────────────────────────┐
│ [Github] https://github.com/aceld                    │
│ [tutorial] https://www.yuque.com/aceld/npyr8s/bgftov │
└──────────────────────────────────────────────────────┘
[Zinx] Version: V1.0, MaxConn: 12000, MaxPacketSize: 4096
===== Zinx Global Config =====
TCPServer: <nil>
Host: 0.0.0.0
TCPPort: 8999
Name: ZinxServerApp
Version: V1.0
MaxPacketSize: 4096
MaxConn: 12000
WorkerPoolSize: 10
MaxWorkerTaskLen: 1024
MaxMsgChanLen: 1024
ConfFilePath: /Users/Aceld/go/src/zinx-usage/quick_start/conf/zinx.json
LogDir: /Users/Aceld/go/src/zinx-usage/quick_start/log
LogFile: 
LogDebugClose: false
HeartbeatMax: 10
==============================
2023/03/09 18:39:49 [INFO]msghandler.go:61: Add api msgID = 1
2023/03/09 18:39:49 [INFO]server.go:112: [START] Server name: ZinxServerApp,listenner at IP: 0.0.0.0, Port 8999 is starting
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 0 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 1 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 3 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 2 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 4 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 6 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 7 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 8 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 9 is started.
2023/03/09 18:39:49 [INFO]msghandler.go:66: Worker ID = 5 is started.
2023/03/09 18:39:49 [INFO]server.go:134: [START] start Zinx server  ZinxServerApp succ, now listenning...

II. Zinx-Client

Starting a client is also very simple, only three steps are needed:

  1. Create a client instance.
  2. Configure some custom business logic for the client.
  3. Start the client.

To quickly start a Zinx client, the code is as follows:

package main

import (
	"fmt"
	"github.com/aceld/zinx/ziface"
	"github.com/aceld/zinx/znet"
	"time"
)

// Custom business logic for the client
func pingLoop(conn ziface.IConnection) {
	for {
		err := conn.SendMsg(1, []byte("Ping...Ping...Ping...[FromClient]"))
		if err != nil {
			fmt.Println(err)
			break
		}

		time.Sleep(1 * time.Second)
	}
}

// Called when creating a connection
func onClientStart(conn ziface.IConnection) {
	fmt.Println("onClientStart is Called ... ")
	go pingLoop(conn)
}

func main() {
	// Create a client instance
	client := znet.NewClient("127.0.0.1", 8999)

	// Set the hook function called after the connection is established
	client.SetOnConnStart(onClientStart)

	// Start the client
	client.Start()

	// Wait for interrupt signals to prevent the process from exiting
	select {}
}

The client will send messages with message ID 1 in a loop. To prevent the client process from exiting, the waitInterrupt() method is added here.

Start the client:

$ go run client.go 
2023/03/09 19:04:54 [INFO]client.go:73: [START] Zinx Client LocalAddr: 127.0.0.1:55294, RemoteAddr: 127.0.0.1:8999
2023/03/09 19:04:54 [INFO]connection.go:354: ZINX CallOnConnStart....

Observe the output on the terminal of the Zinx-Server:

recv from client : msgId= 1 , data= Ping...Ping...Ping...[FromClient]
recv from client : msgId= 1 , data= Ping...Ping...Ping...[FromClient]
recv from client : msgId= 1 , data= Ping...Ping...Ping...[FromClient]
recv from client : msgId= 1 , data= Ping...Ping...Ping...[FromClient]
recv from client : msgId= 1 , data= Ping...Ping...Ping...[FromClient]
recv from client : msgId= 1 , data= Ping...Ping...Ping...[FromClient]
...

In this way, you have built a TCP long connection service based on zinx.

III. Quick Demo of Zinx

If you don't want to write the above code and want to quickly see the effect of Zinx, there is also a quick demo example in the Zinx source code. The specific steps are as follows:

Version Golang 1.16+

$git clone https://github.com/aceld/zinx.git
  1. Compile the demo example. The server will be generated in zinx/example/zinx_server, and the client will be generated in zinx/example/zinx_client.
$ cd zinx/
$ make
  1. Start the Demo server. Do not close this terminal.
$ cd example/zinx_server
$ ./server 
                                        
              ██                        
              ▀▀                        
 ████████   ████     ██▄████▄  ▀██  ██▀ 
     ▄█▀      ██     ██▀   ██    ████   
   ▄█▀        ██     ██    ██    ▄██▄   
 ▄██▄▄▄▄▄  ▄▄▄██▄▄▄  ██    ██   ▄█▀▀█▄  
 ▀▀▀▀▀▀▀▀  ▀▀▀▀▀▀▀▀  ▀▀    ▀▀  ▀▀▀  ▀▀▀ 
                                        
┌───────────────────────────────────────────────────┐
│ [Github] https://github.com/aceld                 │
│ [tutorial] https://www.kancloud.cn/aceld/zinx     │
└───────────────────────────────────────────────────┘
[Zinx] Version: V0.11, MaxConn: 3, MaxPacketSize: 4096
Add api msgId =  0
Add api msgId =  1
[START] Server name: zinx server Demo,listenner at IP: 127.0.0.1, Port 8999 is starting
Worker ID =  0  is started.
Worker ID =  1  is started.
Worker ID =  2  is started.
Worker ID =  3  is started.
Worker ID =  4  is started.
Worker ID =  7  is started.
Worker ID =  6  is started.
Worker ID =  8  is started.
Worker ID =  9  is started.
Worker ID =  5  is started.
start Zinx server   zinx server Demo  succ, now listenning...
...
  1. Open a new terminal and start the client demo to test communication.
$ cd example/zinx_client
$ ./client
==> Test Router:[Ping] Recv Msg: ID= 2 , len= 21 , data= DoConnection BEGIN... ==> Test Router:[Ping] Recv Msg: ID= 0 , len= 18 , data= ping...ping...ping 
==> Test Router:[Ping] Recv Msg: ID= 0 , len= 18 , data= ping...ping...ping
==> Test Router:[Ping] Recv Msg: ID= 0 , len= 18 , data= ping...ping...ping
...
Clone this wiki locally