meim

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 9, 2020 License: MIT Imports: 16 Imported by: 0

README

meim

这并不是一个完整的im,甚至不是一个完整的程序。只是提供了socket服务的一些功能模块,实际应用中需要自己组装。

  1. 固定模块
  • server
    • 提供了 MakeListener,可以注册不同的listener从而满足不同的服务要求
  • client
    • 简单的client内容,以及相关client的读写操作
  • plugin
    • server与client读写过程中的中间操作,在这里实现真正的业务逻辑
  1. 其他
  • router,middleware, example
    • 这些都是在socket业务中会使用到的一些基础工具,只是作为组件放在那里,若不适用,可自定义

Documentation

Index

Constants

View Source
const (
	DefaultReadTimeout  = time.Minute * 15
	DefaultWriteTimeout = time.Second * 10
	DefaultMaxConn      = 65536
)
View Source
const (
	MessageQueueLimit = 1000
)

Variables

View Source
var (
	ErrorInvalidMessage  = errors.New("invalid message")
	ErrorInvalidHeader   = errors.New("invalid header")
	ErrorReadOutofRange  = errors.New("read body length out of range")
	ErrorWriteOutofRange = errors.New("write body length out of range")
)

Functions

func EncodeInternalMessage

func EncodeInternalMessage(message *InternalMessage) ([]byte, error)

func EncodeLimitMessage

func EncodeLimitMessage(message *Message, limitSize int) ([]byte, error)

限制编码消息

func EncodeMessage

func EncodeMessage(message *Message) ([]byte, error)

编码Message

func IsTimeout

func IsTimeout(err error) bool

func RegisterMakeListener

func RegisterMakeListener(network string, ml MakeListener)

RegisterMakeListener registers a MakeListener for network.

func WriteInternalMessage

func WriteInternalMessage(conn io.Writer, msg *InternalMessage) error

func WriteLimitMessage

func WriteLimitMessage(conn io.Writer, message *Message, limitSize int) error

限制写

func WriteMessage

func WriteMessage(conn io.Writer, message *Message) error

write 由服务端自己控制,不用限制字数

Types

type Client

type Client struct {
	UID      int64       // 用户id
	UserData interface{} // 用户其他私有数据
	DC       DataCreator // 协议数据构建器
	Version  int32
	// contains filtered or unexported fields
}

func NewClient

func NewClient(conn Conn) *Client

func (*Client) Close

func (client *Client) Close()

func (*Client) EnqueueEvent

func (client *Client) EnqueueEvent(fn func(*Client)) bool

func (*Client) EnqueueMessage

func (client *Client) EnqueueMessage(msg *Message) bool

发送一般消息

func (*Client) EnqueueNonBlockMessage

func (client *Client) EnqueueNonBlockMessage(msg *Message) bool

发送非阻塞消息

func (*Client) EnsureEvent

func (client *Client) EnsureEvent(fn func(*Client))

如果不能入队列,就直接处理

func (*Client) LocalAddr

func (client *Client) LocalAddr() net.Addr

func (*Client) Log

func (client *Client) Log() string

func (*Client) Run

func (client *Client) Run()

func (*Client) SendLMessages

func (client *Client) SendLMessages()

发送等待队列中的消息

func (*Client) String

func (client *Client) String() string

type ClientSet

type ClientSet map[*Client]struct{}

ClientSet is client set

func NewClientSet

func NewClientSet() ClientSet

func (ClientSet) Add

func (set ClientSet) Add(c *Client)

func (ClientSet) Clone

func (set ClientSet) Clone() ClientSet

只是浅复制

func (ClientSet) Count

func (set ClientSet) Count() int

func (ClientSet) IsMember

func (set ClientSet) IsMember(c *Client) bool

func (ClientSet) Remove

func (set ClientSet) Remove(c *Client)

type Conn

type Conn interface {
	Read([]byte) (int, error)
	Write(b []byte) (int, error) // 写
	RemoteAddr() net.Addr        // 远端地址
	LocalAddr() net.Addr         // 本地地址
	Close() error                // 关闭
}

为什么不直接用net.Conn? 考虑兼容 websocket.Conn等其他情况

type DataCreator

type DataCreator interface {
	CreateHeader() ProtocolHeader
	CreateBody(cmd int) ProtocolBody
	GetCmd(body interface{}) (int, bool)
	GetCmd2(t reflect.Type) (int, bool)
	GetDescription(cmd int) string
}

协议数据创建器,可以分别创建头和body 定义DataCreator的作用之一是,在必要的时候,可以对不同的客户端使用不同的数据交换协议

type Dispatcher

type Dispatcher interface {
	DispatchMessage(*InternalMessage) bool
}

本地消息分发,外部发送到本服务的消息

type Exchanger

type Exchanger struct {
	MessageBroker          //
	Pusher                 //
	InternalMessageHandler //
	// contains filtered or unexported fields
}

Exchanger is just a example 消息交换机,处理消息的对内分发和对外分发 TODO add feedback for not dispatched or not published

func NewMessageExchanger

func NewMessageExchanger(broker MessageBroker, pusher Pusher, handler InternalMessageHandler, router *Router) *Exchanger

func (*Exchanger) DispatchMessage

func (exc *Exchanger) DispatchMessage(msg *InternalMessage) bool

直接下发 单纯的进行消息下发,未考虑业务消息

func (*Exchanger) PublishMessage

func (exc *Exchanger) PublishMessage(msg *InternalMessage) bool

发布消息到Broker

func (*Exchanger) Run

func (exc *Exchanger) Run()

运行一个Exchanger

type ExternalImp

type ExternalImp struct {
	// contains filtered or unexported fields
}

func NewExternalImp

func NewExternalImp() *ExternalImp

func (*ExternalImp) Clone

func (e *ExternalImp) Clone() *ExternalImp

func (*ExternalImp) HandleAuthClient

func (e *ExternalImp) HandleAuthClient(client *Client) bool

func (*ExternalImp) HandleBeforeWriteMessage

func (e *ExternalImp) HandleBeforeWriteMessage(client *Client, message *Message)

func (*ExternalImp) HandleClientClosed

func (e *ExternalImp) HandleClientClosed(client *Client)

func (*ExternalImp) HandleMessage

func (e *ExternalImp) HandleMessage(client *Client, msg *Message)

func (*ExternalImp) SetBeforeWrite

func (e *ExternalImp) SetBeforeWrite(h MessageHandler)

func (*ExternalImp) SetDefaultHandler

func (e *ExternalImp) SetDefaultHandler(h MessageHandler, filters ...Filter)

func (*ExternalImp) SetMsgHandler

func (e *ExternalImp) SetMsgHandler(cmd int, h MessageHandler, filters ...Filter)

func (*ExternalImp) SetOnAuthClient

func (e *ExternalImp) SetOnAuthClient(h func(*Client) bool)

func (*ExternalImp) SetOnClientClosed

func (e *ExternalImp) SetOnClientClosed(h func(*Client))

type ExternalPlugin

type ExternalPlugin interface {
	HandleAuthClient(*Client) bool              // run的第一步, auth 认证客户端,至少确定协议方式,亦即 DataCreator
	HandleMessage(*Client, *Message)            // 消息处理函数
	HandleClientClosed(*Client)                 // 关闭客户端之后的处理
	HandleBeforeWriteMessage(*Client, *Message) //
}

由具体业务实现的方法函数 must

type Filter

type Filter func(MessageHandler) MessageHandler

server和gate 的外部函数实现 example for ExternalPlugin

type InternalMessage

type InternalMessage struct {
	*Message        // 发送的消息体
	Sender    int64 // 发送人
	Receiver  int64 // 接收人
	Timestamp int64 // 时间戳,ms
}

内部消息,服务之间或者组件之间进行消息交换 example

func DecodeInternalMessgae

func DecodeInternalMessgae(b []byte, dc DataCreator) (*InternalMessage, error)

解码

func ReadInternalMessage

func ReadInternalMessage(reader io.Reader, dc DataCreator) (*InternalMessage, error)

编码Message

type InternalMessageHandler

type InternalMessageHandler interface {
	HandleInternalMessage(msg *InternalMessage) // 和Client不一样的地方
}

这个涉及到离线用户的消息处理,只能由业务处理

type ListenerConfig

type ListenerConfig struct {
	Network   string
	Address   string
	TLSConfig *tls.Config
	Options   map[string]interface{} // 为了在不囊括某些配置的时候,能够支持自定义listener的配置信息
}

type MakeListener

type MakeListener func(cfg *ListenerConfig) (ln net.Listener, err error)

listener

type Message

type Message struct {
	Header ProtocolHeader
	Body   ProtocolBody
}

一个完整的消息包含头和body两部分

func DecodeMessage

func DecodeMessage(b []byte, dc DataCreator) (*Message, error)

解码字节流

func ReadLimitMessage

func ReadLimitMessage(reader io.Reader, dc DataCreator, limitSize int) (*Message, error)

限制读

func ReadMessage

func ReadMessage(reader io.Reader, dc DataCreator) (*Message, error)

不限制读

func (*Message) String

func (m *Message) String() string

type MessageBroker

type MessageBroker interface {
	Connect()                                                   // 连接
	Subscribe(uid int64)                                        // 注册用户
	UnSubscribe(uid int64)                                      // 注销用户
	SendMessage(msg *InternalMessage) error                     // 发布消息
	ReceiveMessage() (*InternalMessage, error)                  // 接收消息
	SyncMessage(msg *InternalMessage) (*InternalMessage, error) // 同步消息请求
	Close()
}

分布式用户消息交换

type MessageExchanger

type MessageExchanger interface {
	MessageBroker
	Dispatcher
	Publisher
	InternalMessageHandler
}

消息交换机

type MessageHandler

type MessageHandler func(client *Client, msg *Message)

server和gate 的外部函数实现 example for ExternalPlugin

func FilterRecover

func FilterRecover(fn MessageHandler) MessageHandler

filter 防止panic just for example

type NetConn

type NetConn struct {
	net.Conn
	// contains filtered or unexported fields
}

tcp连接

func NewNetConn

func NewNetConn(conn net.Conn, rto, wto time.Duration) *NetConn

func (*NetConn) Read

func (conn *NetConn) Read(buff []byte) (int, error)

func (*NetConn) Write

func (conn *NetConn) Write(b []byte) (int, error)

type NopPusher

type NopPusher struct{}

func (*NopPusher) PushMessage

func (p *NopPusher) PushMessage(msg *InternalMessage) bool

type OptionFn

type OptionFn func(*Server)

OptionFn 对服务的参数进行插入式配置

func WithExternalPlugin

func WithExternalPlugin(plugin ExternalPlugin) OptionFn

WithExternalPlugin sets server plugin

func WithListenAddr

func WithListenAddr(addr string) OptionFn

WithListenAddr sets listener addr.

func WithMaxConn

func WithMaxConn(n int) OptionFn

WithMaxConn sets maxConn.

func WithNetwork

func WithNetwork(network string) OptionFn

WithWriteTimeout sets writeTimeout.

func WithOptions

func WithOptions(ops map[string]interface{}) OptionFn

WithOptions sets multiple options.

func WithReadTimeout

func WithReadTimeout(readTimeout time.Duration) OptionFn

WithReadTimeout sets readTimeout.

func WithTLSConfig

func WithTLSConfig(cfg *tls.Config) OptionFn

WithTLSConfig sets tls.Config.

func WithWriteTimeout

func WithWriteTimeout(writeTimeout time.Duration) OptionFn

WithWriteTimeout sets writeTimeout.

type ProtocolBody

type ProtocolBody = ProtocolData

协议数据内容

type ProtocolData

type ProtocolData interface {
	Decode(b []byte) error   // 从字节中读取
	Encode() ([]byte, error) // 编码
}

协议数据,定义了数据基本交换协议 头和body 都属于协议数据

type ProtocolHeader

type ProtocolHeader interface {
	ProtocolData
	Length() int
	Cmd() int   // 协议指令
	SetCmd(int) // 指定协议指令
	Seq() int
	SetSeq(int)
	BodyLength() int
	SetBodyLength(n int)
	Ver() int
	SetVer(v int)
	Clone() ProtocolHeader
}

协议头

type Publisher

type Publisher interface {
	PublishMessage(*InternalMessage) bool
}

进行消息发布

type Pusher

type Pusher interface {
	PushMessage(msg *InternalMessage) bool
}

消息推送,作为附属

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router 进行用户客户端管理/查找的路由服务 example

func NewRouter

func NewRouter() *Router

func (*Router) AddClient

func (route *Router) AddClient(client *Client)

uid 已经设置的情况下才可调用 不允许uid为0

func (*Router) FindClient

func (route *Router) FindClient(uid int64) *Client

FindClient 只查找一个在线client

func (*Router) FindClientSet

func (route *Router) FindClientSet(uid int64) ClientSet

func (*Router) IsOnline

func (route *Router) IsOnline(uid int64) bool

func (*Router) RemoveClient

func (route *Router) RemoveClient(client *Client) bool

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server 提供一个连接服务

func NewServer

func NewServer(options ...OptionFn) *Server

新建服务

func NewServerWithConfig

func NewServerWithConfig(cfg *ListenerConfig, options ...OptionFn) *Server

新建服务

func (*Server) ClientSet

func (s *Server) ClientSet() ClientSet

func (*Server) Close

func (s *Server) Close()

func (*Server) Run

func (s *Server) Run()

Directories

Path Synopsis
example
plugins
dc

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL