gonet

package module
v1.1.4-0...-42799e3 Latest Latest
Warning

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

Go to latest
Published: Dec 25, 2023 License: Apache-2.0 Imports: 10 Imported by: 0

README

version

v3.1.0

介绍

一个基于go语言开发的网络脚手架,参考cellnetgin 两大开框架的设计,使用非常方便简洁,轻松让你开发出高并发高性能的网络应用,可以用于游戏,app等任何领域的通讯。

主要技术理念

  • Session pool 会话池
  • Goroutine pool 消息处理协程池
  • Message cache layer 消息缓存层
  • Message sequence 消息排序

架构图

architecture

主要特性及追求目标

  • 高并发
  • 高性能
  • 简单易用
  • 线性安全
  • 兼容性强
  • 高度可配置
  • 多领域应用
  • 防崩溃
  • 错误快速定位

通讯协议支持

  • TCP
  • UDP
  • WEBSOCKET
  • QUIC
  • KCP

数据编码格式支持

  • json
  • xml
  • binary
  • protobuf

安装教程

1. git clone到 GOPATH/src目录下

git clone https://github.com/flylib/gonet.git

使用样例参考

//main.go
package main

import (
	"github.com/flylib/gonet"
	"github.com/flylib/gonet/demo/handler"
	"github.com/flylib/gonet/transport/ws" //协议
	"log"
)

func main() {
	ctx := gonet.NewContext(
		gonet.WithEventHandler(handler.EventHandler{}),

		gonet.MustWithSessionType(transport.SessionType()),
		gonet.MustWithCodec(&json.Codec{}),
		gonet.MustWithLogger(builtinlog.NewLogger()),
	)
	fmt.Println("server listen on ws://localhost:8088/center/ws")
	if err := transport.NewServer(ctx).Listen("ws://localhost:8088/center/ws"); err != nil {
		log.Fatal(err)
	}
}


type EventHandler struct {
}

func (e EventHandler) OnError(session gonet.ISession, err error) {
	println(fmt.Sprintf("sesson-%d error-%v", session, err))
}

func (e EventHandler) OnConnect(session gonet.ISession) {
	fmt.Println(fmt.Sprintf("new session-%d from-%s", session.ID(), session.RemoteAddr()))
}

func (e EventHandler) OnClose(session gonet.ISession, err error) {
	//TODO implement me
	fmt.Println(fmt.Sprintf("session close-%d", session.ID()))
}

func (e EventHandler) OnMessage(message gonet.IMessage) {
	//TODO implement me
	switch message.ID() {
	case 101:
		fmt.Println("session-", message.From().ID(), " say:", string(message.Body()))
	}
}

测试

FAQ

参与贡献

QQ群:795611332

Documentation

Index

Constants

View Source
const (
	MTU           = 1500                      // 最大传输单元
	PktSizeOffset = 2                         // 包体大小字段
	MsgIDOffset   = 4                         // 消息ID字段
	HeaderOffset  = MsgIDOffset + MsgIDOffset //包头部分
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {

	//message codec
	codec.ICodec
	ilog.ILogger
	//net package parser
	INetPackager
	// contains filtered or unexported fields
}

func NewContext

func NewContext(options ...Option) *Context

func (*Context) Broadcast

func (c *Context) Broadcast(msgId uint32, msg any)

func (*Context) GetEventHandler

func (c *Context) GetEventHandler() IEventHandler

func (*Context) GetIdleSession

func (c *Context) GetIdleSession() ISession

func (*Context) GetSession

func (c *Context) GetSession(id uint64) (ISession, bool)

会话管理

func (*Context) PushGlobalMessageQueue

func (c *Context) PushGlobalMessageQueue(msg IMessage)

push the message to the routine pool

func (*Context) RecycleSession

func (c *Context) RecycleSession(session ISession)

func (*Context) SessionCount

func (c *Context) SessionCount() int32

type DefaultNetPackager

type DefaultNetPackager struct {
}

func (*DefaultNetPackager) Package

func (d *DefaultNetPackager) Package(s ISession, msgID uint32, v any) ([]byte, error)

func (*DefaultNetPackager) UnPackage

func (d *DefaultNetPackager) UnPackage(s ISession, data []byte) (IMessage, int, error)

type GoroutinePool

type GoroutinePool struct {
	*Context
	// contains filtered or unexported fields
}

Lightweight goroutine pool

type IClient

type IClient interface {
	Dial(addr string) (ISession, error)
	Close() error
}

client interface

type IEventHandler

type IEventHandler interface {
	OnConnect(ISession)
	OnClose(ISession, error)
	OnMessage(IMessage)
	OnError(ISession, error)
}

type IMessage

type IMessage interface {
	ID() uint32
	Body() []byte
	From() ISession
	UnmarshalTo(v any) error
}

type INetPackager

type INetPackager interface {
	Package(s ISession, msgID uint32, v any) ([]byte, error)
	UnPackage(s ISession, data []byte) (IMessage, int, error)
}

网络包解析器(network package)

type IServer

type IServer interface {
	Listen(addr string) error
	Close() error
	Addr() string
}

server interface

type ISession

type ISession interface {
	//ID
	ID() uint64
	//close the connection
	Close() error
	//send the message to the other side
	Send(msgID uint32, msg any) error
	//remote addr
	RemoteAddr() net.Addr
	//convenient session storage data
	Store(value any)
	//load the data
	Load() (value any)
	//get the working Context
	GetContext() *Context
}

type Option

type Option func(o *Context)

func MustWithCodec

func MustWithCodec(codec codec.ICodec) Option

Default json codec, message codec

func MustWithLogger

func MustWithLogger(l ilog.ILogger) Option

set logger

func MustWithSessionType

func MustWithSessionType(t reflect.Type) Option

set SessionType

func WithEventHandler

func WithEventHandler(handler IEventHandler) Option

Default:0 means is no limit

func WithGQSize

func WithGQSize(size int32) Option

Default 512,global queue size

func WithMaxSessions

func WithMaxSessions(max int) Option

Default:0 means is no limit

func WithNetPackager

func WithNetPackager(packager INetPackager) Option

network package paser

func WithPoolMaxIdleRoutines

func WithPoolMaxIdleRoutines(num int32) Option

allow max idle routines

func WithPoolMaxRoutines

func WithPoolMaxRoutines(num int32) Option

Default is runtime.NumCPU(), means no goroutines will be dynamically scaled

type PeerCommon

type PeerCommon struct {
	*Context
	// contains filtered or unexported fields
}

func (*PeerCommon) Addr

func (s *PeerCommon) Addr() string

func (*PeerCommon) SetAddr

func (s *PeerCommon) SetAddr(addr string)

func (*PeerCommon) WithContext

func (s *PeerCommon) WithContext(c *Context)

type SessionCommon

type SessionCommon struct {
	atomic.Value
	spinlock.Locker
	// contains filtered or unexported fields
}

核心会话标志

func (*SessionCommon) Clear

func (s *SessionCommon) Clear()

func (*SessionCommon) GetContext

func (s *SessionCommon) GetContext() *Context

func (*SessionCommon) ID

func (s *SessionCommon) ID() uint64

func (*SessionCommon) SetID

func (s *SessionCommon) SetID(id uint64)

func (*SessionCommon) UpdateID

func (s *SessionCommon) UpdateID(id uint64)

func (*SessionCommon) WithContext

func (s *SessionCommon) WithContext(c *Context)

type TransportProtocol

type TransportProtocol string
const (
	TCP  TransportProtocol = "tcp"
	KCP  TransportProtocol = "kcp"
	UDP  TransportProtocol = "udp"
	WS   TransportProtocol = "websocket"
	HTTP TransportProtocol = "http"
	QUIC TransportProtocol = "quic"
	RPC  TransportProtocol = "rpc"
)

Directories

Path Synopsis
transport
gnet Module
kcp Module
quic Module
tcp Module
udp Module
ws Module

Jump to

Keyboard shortcuts

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