Browse Source

Merge pull request #94 from gufeijun/master

merge from gufeijun/master
master
刘丹冰 4 years ago
committed by GitHub
parent
commit
cae3bc3252
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      ziface/iconnection.go
  2. 26
      znet/connection.go

8
ziface/iconnection.go

@ -1,6 +1,9 @@
package ziface
import "net"
import (
"context"
"net"
)
//定义连接接口
type IConnection interface {
@ -8,7 +11,8 @@ type IConnection interface {
Start()
//停止连接,结束当前连接状态M
Stop()
//返回ctx,用于用户自定义的go程获取连接退出状态
Context() context.Context
//从当前连接获取原始的socket TCPConn
GetTCPConnection() *net.TCPConn
//获取当前连接ID

26
znet/connection.go

@ -49,7 +49,7 @@ func NewConntion(server ziface.IServer, conn *net.TCPConn, connID uint32, msgHan
MsgHandler: msgHandler,
msgChan: make(chan []byte),
msgBuffChan: make(chan []byte, utils.GlobalObject.MaxMsgChanLen),
property: make(map[string]interface{}),
property: nil,
}
//将新创建的Conn添加到链接管理中
@ -162,20 +162,20 @@ func (c *Connection) Start() {
//停止连接,结束当前连接状态M
func (c *Connection) Stop() {
fmt.Println("Conn Stop()...ConnID = ", c.ConnID)
c.Lock()
defer c.Unlock()
//如果用户注册了该链接的关闭回调业务,那么在此刻应该显示调用
c.TcpServer.CallOnConnStop(c)
//如果当前链接已经关闭
if c.isClosed == true {
return
}
c.isClosed = true
fmt.Println("Conn Stop()...ConnID = ", c.ConnID)
//如果用户注册了该链接的关闭回调业务,那么在此刻应该显示调用
c.TcpServer.CallOnConnStop(c)
// 关闭socket链接
c.Conn.Close()
//关闭Writer
@ -206,11 +206,10 @@ func (c *Connection) RemoteAddr() net.Addr {
//直接将Message数据发送数据给远程的TCP客户端
func (c *Connection) SendMsg(msgId uint32, data []byte) error {
c.RLock()
defer c.RUnlock()
if c.isClosed == true {
c.RUnlock()
return errors.New("connection closed when send msg")
}
c.RUnlock()
//将data封包,并且发送
dp := NewDataPack()
@ -228,11 +227,10 @@ func (c *Connection) SendMsg(msgId uint32, data []byte) error {
func (c *Connection) SendBuffMsg(msgId uint32, data []byte) error {
c.RLock()
defer c.RUnlock()
if c.isClosed == true {
c.RUnlock()
return errors.New("Connection closed when send buff msg")
}
c.RUnlock()
//将data封包,并且发送
dp := NewDataPack()
@ -252,6 +250,9 @@ func (c *Connection) SendBuffMsg(msgId uint32, data []byte) error {
func (c *Connection) SetProperty(key string, value interface{}) {
c.propertyLock.Lock()
defer c.propertyLock.Unlock()
if c.property == nil {
c.property = make(map[string]interface{})
}
c.property[key] = value
}
@ -275,3 +276,8 @@ func (c *Connection) RemoveProperty(key string) {
delete(c.property, key)
}
//返回ctx,用于用户自定义的go程获取连接退出状态
func (c *Connection) Context() context.Context {
return c.ctx
}
Loading…
Cancel
Save