tcplibrary

package module
v0.0.0-...-4279368 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2018 License: MIT Imports: 15 Imported by: 0

README

golang的tcp通讯库

使用此库你只需要创建一个server或client的结构体,实现接口,再写两句话就可以搭建起tcp通讯

备注

自定义协议的小伙伴如果需要websocket通讯时,请参考default_packet.go中的GetPayload()函数,包内容问题

当需要获取连接列表时 可以调用GetClients()方法获取连接*sync.Map

Documentation

Overview

* @Author: 时光弧线 * @Date: 2017-12-30 11:54:57 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 13:11:34

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:02 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 13:09:56

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:06 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 11:55:06

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:15 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 14:02:48

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:19 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 13:13:07

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:26 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 13:22:12

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:33 * @Last Modified by: 时光弧线 * @Last Modified time: 2018-10-21 14:41:00

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:38 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 13:14:28

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:41 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 13:22:40

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:47 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 13:48:57

* @Author: 时光弧线 * @Date: 2017-12-30 11:55:50 * @Last Modified by: 时光弧线 * @Last Modified time: 2017-12-30 13:23:42

Index

Constants

View Source
const (
	// TCPSocketType tcp连接
	TCPSocketType = iota
	// WebSocketType WebSocket连接
	WebSocketType
)

Variables

View Source
var (
	DefaultBufferSize         = 1024
	DefaultMessageChannelSize = 32
	DefaultReadDeadline       = 15 * time.Second
)

定义的tcp读缓存区大小

Functions

func ByteToBool

func ByteToBool(i byte) bool

func BytesToInt

func BytesToInt(data []byte) int

func BytesToInt16

func BytesToInt16(data []byte) int16

func BytesToInt32

func BytesToInt32(data []byte) int32

func BytesToInt64

func BytesToInt64(data []byte) int64

func BytesToUint16

func BytesToUint16(data []byte) uint16

func BytesToUint32

func BytesToUint32(data []byte) uint32

func BytesToUint64

func BytesToUint64(data []byte) uint64

func Float32bytes

func Float32bytes(float float32) []byte

func Float64frombytes

func Float64frombytes(bytes []byte) float64

func IntToBytes

func IntToBytes(data interface{}) []byte

IntToBytes 整形转换成byte数组

func SetGlobalLogger

func SetGlobalLogger(logger TCPLibraryLogger)

SetGlobalLogger 设置日志对象

Types

type Conn

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

Conn 自定义连接对象结构体,可以存储tcp或webSocket连接对象

func (*Conn) GetClientID

func (c *Conn) GetClientID() string

GetClientID 获取当前连接id

func (*Conn) GetConnType

func (c *Conn) GetConnType() TCPType

GetConnType 获取连接类型

func (*Conn) SendMessage

func (c *Conn) SendMessage(v interface{}) (int, error)

SendMessage 发送消息,参数为自己报文结构体

type DefaultPacket

type DefaultPacket struct {
	Length         int32            `json:"Length"`  // Payload 包长度,4字节
	Payload        interface{}      `json:"Payload"` // 报文内容,n字节
	WebsocketCodec *websocket.Codec `json:"-"`
}

DefaultPacket 协议包

func NewDefaultPacket

func NewDefaultPacket() *DefaultPacket

NewDefaultPacket 创建解包封包对象

func (*DefaultPacket) GetPayload

func (dp *DefaultPacket) GetPayload() []byte

GetPayload 获取包内容 之所以有此函数,是为了兼容websocket,websocket使用此库时可直接使用json传输数据

func (*DefaultPacket) GetWebsocketCodec

func (dp *DefaultPacket) GetWebsocketCodec() *websocket.Codec

GetWebsocketCodec 获取websocket编解码对象

func (*DefaultPacket) Marshal

func (dp *DefaultPacket) Marshal(v interface{}) ([]byte, error)

Marshal 默认封包

func (*DefaultPacket) MarshalToJSON

func (dp *DefaultPacket) MarshalToJSON(v interface{}) (data []byte, payloadType byte, err error)

MarshalToJSON 编码到json, 同时将Payload转为字符串

func (*DefaultPacket) Unmarshal

func (dp *DefaultPacket) Unmarshal(data []byte, c chan interface{}) (outData []byte, err error)

Unmarshal 默认解包

func (*DefaultPacket) UnmarshalToJSON

func (dp *DefaultPacket) UnmarshalToJSON(data []byte, payloadType byte, v interface{}) (err error)

UnmarshalToJSON 解包为json字符串形式

type Logger

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

Logger 日志记录

func (*Logger) Errorf

func (l *Logger) Errorf(format string, a ...interface{})

Errorf 打印错误 Error

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, a ...interface{})

Fatalf 打印错误 Fatal

func (*Logger) Infof

func (l *Logger) Infof(format string, a ...interface{})

Infof 打印错误 Info

func (*Logger) SetDefaultDebug

func (l *Logger) SetDefaultDebug(debug bool)

SetDefaultDebug 设置是否为debug模式 - 只对默认日志库生效

func (*Logger) Warnf

func (l *Logger) Warnf(format string, a ...interface{})

Warnf 打印错误 Warn

type Packet

type Packet interface {
	Unmarshal(data []byte, c chan interface{}) ([]byte, error)                // 解包
	Marshal(v interface{}) ([]byte, error)                                    // 封包
	MarshalToJSON(v interface{}) (data []byte, payloadType byte, err error)   // 封包为json字符串形式
	UnmarshalToJSON(data []byte, payloadType byte, v interface{}) (err error) // 解包为json字符串形式
	GetWebsocketCodec() *websocket.Codec
}

Packet 封包和解包

type ServerSocket

type ServerSocket interface {
	Socket
	GetClientID() string // 获取session id生成规则
}

ServerSocket 服务接口,实例化tcp server时传次参数

type Socket

type Socket interface {
	OnConnect(*Conn) error                            // 连接建立时
	OnError(error)                                    // 连接发生错误
	OnClose(*Conn, error)                             // 关闭连接时
	OnRecMessage(context.Context, *Conn, interface{}) // 接收消息时
}

Socket tcp通讯需要的一些回调函数

type TCPClient

type TCPClient struct {
	*TCPLibrary
	// contains filtered or unexported fields
}

TCPClient tcp客户端

func NewTCPClient

func NewTCPClient(debug bool, socket Socket, packets ...Packet) (*TCPClient, error)

NewTCPClient 创建一个tcp客户端

func (*TCPClient) Dial

func (c *TCPClient) Dial(conn net.Conn) error

Dial 连接tcp服务端

func (*TCPClient) DialAndStart

func (c *TCPClient) DialAndStart(address string) error

DialAndStart 连接到服务器,并开始读取信息

func (*TCPClient) DialAndStartTLS

func (c *TCPClient) DialAndStartTLS(address string) error

DialAndStartTLS 连接到服务器,并开始读取信息 tls

func (*TCPClient) GetConn

func (c *TCPClient) GetConn() *Conn

GetConn 获取连接对象

func (*TCPClient) Ping

func (c *TCPClient) Ping(v interface{})

Ping 保活

type TCPLibrary

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

TCPLibrary tcp库父类 - 每实例化

func NewTCPLibrary

func NewTCPLibrary(debug bool, socket ServerSocket, packets ...Packet) (*TCPLibrary, error)

NewTCPLibrary 创建TCPLibrary对象 - 只用于创建服务端对象时使用,客户端直接使用 NewTCPClient

func (*TCPLibrary) CloseForClientID

func (t *TCPLibrary) CloseForClientID(clientID string) error

CloseForClientID 根据clientID关闭连接

func (*TCPLibrary) GetClients

func (t *TCPLibrary) GetClients() *sync.Map

GetClients 获取客户端列表,在自己的业务中使用,使用时切记小心操作

func (*TCPLibrary) NewTCPServer

func (t *TCPLibrary) NewTCPServer() *TCPServer

NewTCPServer 创建一个server实例

func (*TCPLibrary) NewWebSocketServer

func (t *TCPLibrary) NewWebSocketServer() *WebSocketServer

NewWebSocketServer 创建一个websocket监听

func (*TCPLibrary) SendMessageToAll

func (t *TCPLibrary) SendMessageToAll(v interface{}) (int, error)

SendMessageToAll 发送给所有客户端 只有服务端可调用

func (*TCPLibrary) SendMessageToClients

func (t *TCPLibrary) SendMessageToClients(v interface{}, clientIDs ...string) (sendCount int, err error)

SendMessageToClients 发送数据给指定客户端 返回值,第一个值为发送成功几个连接 只有服务端可调用

func (*TCPLibrary) SetReadBufferSize

func (t *TCPLibrary) SetReadBufferSize(readBufferSize int)

SetReadBufferSize 设置参数 readBufferSize

func (*TCPLibrary) SetReadDeadline

func (t *TCPLibrary) SetReadDeadline(duration time.Duration)

SetReadDeadline 设置参数 readDeadline

func (*TCPLibrary) StopService

func (t *TCPLibrary) StopService() (err error)

StopService 停止服务

type TCPLibraryLogger

type TCPLibraryLogger interface {
	Infof(format string, a ...interface{})
	Warnf(format string, a ...interface{})
	Errorf(format string, a ...interface{})
	Fatalf(format string, a ...interface{})
}

TCPLibraryLogger 日志接口,可以使用第三方日志库,符合接口即可

type TCPServer

type TCPServer struct {
	*TCPLibrary
	// contains filtered or unexported fields
}

TCPServer tcp服务端对象

func (*TCPServer) ListenAndServe

func (tcp *TCPServer) ListenAndServe(address string) error

ListenAndServe 开始tcp监听

func (*TCPServer) ListenAndServeTLS

func (tcp *TCPServer) ListenAndServeTLS(address, certFile, keyFile string) error

ListenAndServeTLS 开始tcp监听 tls

func (*TCPServer) Serve

func (tcp *TCPServer) Serve(listen net.Listener) error

Serve 开启服务

type TCPType

type TCPType = int

TCPType tcp连接类型

type WebSocketServer

type WebSocketServer struct {
	*TCPLibrary
	// contains filtered or unexported fields
}

WebSocketServer websocket 服务端操作对象

func (*WebSocketServer) ListenAndServe

func (ws *WebSocketServer) ListenAndServe(address, route string) error

ListenAndServe 开始ws监听 address 监听的地址和端口 route 监听的路由(url)

func (*WebSocketServer) ListenAndServeTLS

func (ws *WebSocketServer) ListenAndServeTLS(address, certFile, keyFile, route string) error

ListenAndServeTLS 开始ws监听 tls address 监听的地址和端口 route 监听的路由(url)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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