Zinx-V0.10
This commit is contained in:
parent
c0f55440ba
commit
88a4caf72e
@ -1,6 +1,9 @@
|
||||
package ziface
|
||||
|
||||
import "net"
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
)
|
||||
|
||||
type IConnection interface {
|
||||
// Start 启动连接
|
||||
@ -17,4 +20,8 @@ type IConnection interface {
|
||||
SendMsg(msgID uint32, data []byte) error
|
||||
// SendBuffMsg 发送数据,将数据发送给远程的客户端(有缓冲)
|
||||
SendBuffMsg(msgID uint32, data []byte) error
|
||||
// SetContext 设置当前连接的上下文
|
||||
SetContext(ctx context.Context)
|
||||
// GetContext 获取当前连接的上下文
|
||||
GetContext() context.Context
|
||||
}
|
||||
|
@ -36,7 +36,6 @@ type Connection struct {
|
||||
// NewConnection 创建连接的方法
|
||||
func NewConnection(server ziface.IServer, conn *net.TCPConn, connID uint32, msgHandler ziface.IMsgHandle) *Connection {
|
||||
c := &Connection{
|
||||
ctx: context.Background(),
|
||||
TcpServer: server,
|
||||
Conn: conn,
|
||||
ConnID: connID,
|
||||
@ -238,6 +237,11 @@ func (c *Connection) SendBuffMsg(msgID uint32, data []byte) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetContext 设置当前连接的上下文
|
||||
func (c *Connection) SetContext(ctx context.Context) {
|
||||
c.ctx = ctx
|
||||
}
|
||||
|
||||
// GetContext 获取当前连接的上下文
|
||||
func (c *Connection) GetContext() context.Context {
|
||||
return c.ctx
|
||||
|
@ -1,6 +1,7 @@
|
||||
package znet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"go-study/zinx/ziface"
|
||||
"net"
|
||||
@ -43,6 +44,12 @@ func (h *HelloZinxRouter) Handle(request ziface.IRequest) {
|
||||
// DoConnectionBegin 创建连接之后执行的钩子函数
|
||||
func DoConnectionBegin(conn ziface.IConnection) {
|
||||
fmt.Println("DoConnectionBegin is Called ... ")
|
||||
|
||||
ctx := context.WithValue(context.Background(), "Name", "fantasticbin")
|
||||
ctx = context.WithValue(ctx, "Home", "https://www.fantasticbin.com")
|
||||
conn.SetContext(ctx)
|
||||
fmt.Println("Set conn Name, Home done!")
|
||||
|
||||
if err := conn.SendMsg(2, []byte("DoConnection BEGIN")); err != nil {
|
||||
fmt.Println("DoConnectionBegin error:", err)
|
||||
}
|
||||
@ -50,6 +57,17 @@ func DoConnectionBegin(conn ziface.IConnection) {
|
||||
|
||||
// DoConnectionLost 连接断开之前执行的钩子函数
|
||||
func DoConnectionLost(conn ziface.IConnection) {
|
||||
// 断开连接时,获取连接的上下文信息
|
||||
ctx := conn.GetContext()
|
||||
if ctx != nil {
|
||||
if name := ctx.Value("Name"); name != nil {
|
||||
fmt.Println("ConnID =", conn.GetConnID(), " get Name from Context =", name)
|
||||
}
|
||||
if home := ctx.Value("Home"); home != nil {
|
||||
fmt.Println("ConnID =", conn.GetConnID(), " get Home from Context =", home)
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println("DoConnectionLost is Called ... ")
|
||||
fmt.Println("conn ID =", conn.GetConnID(), " is lost...")
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user