7. Building Zinx's Read-Write Separation Model
Tags: zinx, go
Published: 2023-07-03 07:18:27

### [Zinx]

[<1.Building Basic Services with Zinx Framework>](https://dev.to/aceld/1building-basic-services-with-zinx-framework-296e)
[<2. Zinx-V0.2 Simple Connection Encapsulation and Binding with Business>](https://dev.to/aceld/2-zinx-v02-simple-connection-encapsulation-and-binding-with-business-4p9g)
[<3.Design and Implementation of the Zinx Framework's Routing Module>](https://dev.to/aceld/3design-and-implementation-of-the-zinx-frameworks-routing-module-583n)
[<4.Zinx Global Configuration>](https://dev.to/aceld/4zinx-global-configuration-3jam)
[<5.Zinx Message Encapsulation Module Design and Implementation>](https://dev.to/aceld/5zinx-message-encapsulation-module-design-and-implementation-3fmc)
[<6.Design and Implementation of Zinx Multi-Router Mode>](https://dev.to/aceld/6design-and-implementation-of-zinx-multi-router-mode-19nn)
[<7. Building Zinx's Read-Write Separation Model>](https://dev.to/aceld/7-building-zinxs-read-write-separation-model-ihj)
[<8.Zinx Message Queue and Task Worker Pool Design and Implementation>](https://dev.to/aceld/8zinx-message-queue-and-task-worker-pool-design-and-implementation-12gl)
[<9. Zinx Connection Management and Property Setting>](https://dev.to/aceld/9-zinx-connection-management-and-property-setting-28ha)

### [Zinx Application - MMO Game Case Study]

[<10. Application Case Study using the Zinx Framework>](https://dev.to/aceld/10-application-case-study-using-the-zinx-framework-3ich)
[<11. MMO Online Game AOI Algorithm>](https://dev.to/aceld/11-mmo-online-game-aoi-algorithm-l7d)
[<12.Data Transmission Protocol: Protocol Buffers>](https://dev.to/aceld/12data-transmission-protocol-protocol-buffers-1jek)
[<13. MMO Game Server Application Protocol>](https://dev.to/aceld/13-mmo-game-server-application-protocol-5adl)
[<14. Building the Project and User Login>](https://dev.to/aceld/14-building-the-project-and-user-login-b7p)
[<15. World Chat System Implementation>](https://dev.to/aceld/157-world-chat-system-implementation-18li)
[<16. Online Location Information Synchronization>](https://dev.to/aceld/16-online-location-information-synchronization-3cp1)
[<17. Moving position and non-crossing grid AOI broadcasting>](https://dev.to/aceld/17-moving-position-and-non-crossing-grid-aoi-broadcasting-4nb9)
[<18. Player Logout>](https://dev.to/aceld/18-player-logout-3eln)
[<19. Movement and AOI Broadcast Across Grids>](https://dev.to/aceld/19-movement-and-aoi-broadcast-across-grids-46fe)

---

## source code
https://github.com/aceld/zinx/blob/master/examples/zinx_release/zinx-v0.7.tar.gz

---


In this chapter, we will make a minor modification to Zinx to upgrade it with a new version that separates the read and write operations with the client into two separate Goroutines. One Goroutine will be responsible for reading data from the client, while the other will be responsible for writing data to the client. This design provides benefits such as high cohesion and modularized functionality, making it easier to expand the system's capabilities in the future. The updated read-write architecture is illustrated in Figure 7.1.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6kgi5nqevo2col402mxq.png)
> Figure 18.1: Read-Write Separation Model

The server continues to handle client responses and includes the key methods from before, such as `Listen()` and `Accept()`. Once a socket connection is established with the client, two Goroutines are launched to handle the read and write operations separately. Messages between the read and write processes are passed through a channel.

## 7.1 Implementation of Zinx-V0.7 Code

The code modifications for the read-write separation model are as follows. The changes are minimal, involving four areas of improvement.

### 7.1.1 Adding a communication channel for the read-write modules

First, we need to add a communication channel between the two Goroutines for reading and writing. This channel will be used to transmit signal and status data between the two Goroutines. We define this channel in the `Connection` struct since both the reading and writing Goroutines will operate on the current connection that has already been established. The updated `Connection` data structure is as follows:

```go
// zinx/znet/connection.go

type Connection struct {
	// Current TCP socket connection
	Conn *net.TCPConn
	// Unique ID for the connection, also known as SessionID
	ConnID uint32
	// Connection close status
	isClosed bool
	// Message handler module that manages message IDs and corresponding processing methods
	MsgHandler ziface.IMsgHandle
	// Channel to signal that the connection has exited/stopped
	ExitBuffChan chan bool
	// Unbuffered channel for message communication between the read and write Goroutines
	msgChan chan []byte
}
```

We add a new channel member, `msgChan`, to `Connection`. Its purpose is to facilitate communication between the read and write Goroutines. Additionally, the construction method for `Connection` needs to initialize the `msgChan` attribute. The modified code is as follows:
```go
// Create a connection method
func NewConnection(conn *net.TCPConn, connID uint32, msgHandler ziface.IMsgHandle) *Connection {
	c := &Connection{
		Conn:          conn,
		ConnID:        connID,
		isClosed:      false,
		MsgHandler:    msgHandler,
		ExitBuffChan:  make(chan bool, 1),
		msgChan:       make(chan []byte), // Initialize msgChan
	}

	return c
}
```

### 7.1.2 Creating the Writer Goroutine:

We need to write a Goroutine for sending messages to the client. The core code involves invoking `conn.Write()`, and the logic waits for messages sent by the read Goroutine. The code is as follows:

```go
// zinx/znet/connection.go

/*
	Writer Goroutine: Sends data to the client
*/
func (c *Connection) StartWriter() {
	fmt.Println("[Writer Goroutine is running]")
	defer fmt.Println(c.RemoteAddr().String(), "[conn Writer exit!]")

	for {
		select {
		case data := <-c.msgChan:
			// Data to be written to the client
			if _, err := c.Conn.Write(data); err != nil {
				fmt.Println("Send Data error:", err, "Conn Writer exit")
				return
			}
		case <-c.ExitBuffChan:
			// Connection has been closed
			return
		}
	}
}
```

The advantage of creating the `StartWriter()` Goroutine is that it separates the reading and writing business logic, making the responsibilities clear and allowing for independent optimization of either the read or write process without interfering with each other.

### 7.1.3 Modifying the Reader to send data to the Channel:

We need to modify the SendMsg() method called by the Reader to send messages to the Writer instead of directly writing back to the client. The relevant code is as follows:

```go
// zinx/znet/connection.go

// Send Message: Send message data directly to the remote TCP client
func (c *Connection) SendMsg(msgID uint32, data []byte) error {
	if c.isClosed == true {
		return errors.New("Connection closed when sending message")
	}

	// Package the data and send it
	dp := NewDataPack()
	msg, err := dp.Pack(NewMsgPackage(msgID, data))
	if err != nil {
		fmt.Println("Pack error, msgID =", msgID)
		return errors.New("Pack error message")
	}

	// Write back to the client
	// Change the previous direct write using conn.Write to sending the message to the Channel for the Writer to read
	c.msgChan <- msg

	return nil
}
```

### 7.1.4 Starting the Reader and Writer:

The logic for starting the connection becomes clearer. We only need to start the Reader and Writer Goroutines separately to handle the connection's read and write operations. The code for starting the connection is as follows:

```go
// zinx/znet/connection.go

// Start the connection and make it work
func (c *Connection) Start() {
	// 1. Start a Goroutine for reading data from the client
	go c.StartReader()
	// 2. Start a Goroutine for writing data back to the client
	go c.StartWriter()

	for {
		select {
		case <-c.ExitBuffChan:
			// Received exit message, no longer block
			return
		}
	}
}
```

## 7.2 Summary
The testing code remains the same as in V0.6, so it will not be reiterated here. We have successfully separated the read and write modules. The significance of the read-write separation design is that it provides a clear direction for future improvements, allowing for targeted optimizations of either the read or write processes. The next step would be to further upgrade based on this read-write separation by adding a task queue mechanism.


---
### [Zinx]

[<1.Building Basic Services with Zinx Framework>](https://dev.to/aceld/1building-basic-services-with-zinx-framework-296e)
[<2. Zinx-V0.2 Simple Connection Encapsulation and Binding with Business>](https://dev.to/aceld/2-zinx-v02-simple-connection-encapsulation-and-binding-with-business-4p9g)
[<3.Design and Implementation of the Zinx Framework's Routing Module>](https://dev.to/aceld/3design-and-implementation-of-the-zinx-frameworks-routing-module-583n)
[<4.Zinx Global Configuration>](https://dev.to/aceld/4zinx-global-configuration-3jam)
[<5.Zinx Message Encapsulation Module Design and Implementation>](https://dev.to/aceld/5zinx-message-encapsulation-module-design-and-implementation-3fmc)
[<6.Design and Implementation of Zinx Multi-Router Mode>](https://dev.to/aceld/6design-and-implementation-of-zinx-multi-router-mode-19nn)
[<7. Building Zinx's Read-Write Separation Model>](https://dev.to/aceld/7-building-zinxs-read-write-separation-model-ihj)
[<8.Zinx Message Queue and Task Worker Pool Design and Implementation>](https://dev.to/aceld/8zinx-message-queue-and-task-worker-pool-design-and-implementation-12gl)
[<9. Zinx Connection Management and Property Setting>](https://dev.to/aceld/9-zinx-connection-management-and-property-setting-28ha)

### [Zinx Application - MMO Game Case Study]

[<10. Application Case Study using the Zinx Framework>](https://dev.to/aceld/10-application-case-study-using-the-zinx-framework-3ich)
[<11. MMO Online Game AOI Algorithm>](https://dev.to/aceld/11-mmo-online-game-aoi-algorithm-l7d)
[<12.Data Transmission Protocol: Protocol Buffers>](https://dev.to/aceld/12data-transmission-protocol-protocol-buffers-1jek)
[<13. MMO Game Server Application Protocol>](https://dev.to/aceld/13-mmo-game-server-application-protocol-5adl)
[<14. Building the Project and User Login>](https://dev.to/aceld/14-building-the-project-and-user-login-b7p)
[<15. World Chat System Implementation>](https://dev.to/aceld/157-world-chat-system-implementation-18li)
[<16. Online Location Information Synchronization>](https://dev.to/aceld/16-online-location-information-synchronization-3cp1)
[<17. Moving position and non-crossing grid AOI broadcasting>](https://dev.to/aceld/17-moving-position-and-non-crossing-grid-aoi-broadcasting-4nb9)
[<18. Player Logout>](https://dev.to/aceld/18-player-logout-3eln)
[<19. Movement and AOI Broadcast Across Grids>](https://dev.to/aceld/19-movement-and-aoi-broadcast-across-grids-46fe)

---

## source code
https://github.com/aceld/zinx/blob/master/examples/zinx_release/zinx-v0.7.tar.gz

---
Author:
discord: https://discord.gg/xQ8Xxfyfcz
zinx:   https://github.com/aceld/zinx
github: https://github.com/aceld
aceld's home: https://yuque.com/aceld