gudp

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

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

Go to latest
Published: Sep 13, 2023 License: MIT Imports: 19 Imported by: 0

README

gudp

简介

gudpgodot game 所实现,提供轻量快速的可靠udp实现, 用户通过简单的函数即可快速搭建可靠的udp服务。

godot-client点击访问

使用mit协议开源,支持通过fork进行贡献。

特性

  1. 支持可靠消息、不可靠消息
  2. 支持身份认证
  3. 内置支持重发和心跳检测
  4. 使用proto作为通用协议
  5. 支持rpc协议(udp实现)

使用方式


package main

import (
	"errors"
	"fmt"
	"github.com/rr13k/gudp"
	"google.golang.org/protobuf/proto"
)

var GudpServer *gudp.Server

func main() {
	host := "127.0.0.1"
	port := 12345

	var err error

	udpConn := gudp.CreateUdpConn(host, port)
	GudpServer, err = gudp.NewServerManager(udpConn)
	if err != nil {
		fmt.Println(err.Error())
	}
    
	GudpServer.SetHandler(onReceived)
	go func() { // handling the server errors
		for {
			uerr := <-GudpServer.Error
			if uerr != nil {
				fmt.Println("Errors on udp server: ", uerr.Error())
			}
		}
	}()

	GudpServer.Serve()
}

// 当接受到消息触发
func onReceived(client *gudp.Client, buffer []byte) {
	fmt.Println("on msg:", buffer)
	var hi = []byte("hello world~")
	// 发送可靠消息
	GudpServer.SendClientMessage(client, hi, true)
	// 发送不可靠消息
	GudpServer.SendClientMessage(client, hi, false)
}

使用rpc

GudpServer, err = gudp.NewServerManager(udpConn)
if err != nil {
	fmt.Println(err.Error())
}
// NewServerManager连接后,配置rpc结构体
GudpServer.RegisterRpc(new(rpcs.UdpRpc))


// rpcs.go 文件中
type UdpRpc struct {
}

// 算数运算请求结构体
type UdpRpcRequest struct {
	A int
	B int
}

// 算数运算响应结构体
type UdpRpcResponse struct {
	Pro int // 乘积
	Quo int // 商
	Rem int // 余数
}

// 基础测试
func (u *UdpRpc) Multiply(req UdpRpcRequest, res *UdpRpcResponse) error {
	res.Pro = req.A * req.B
	fmt.Println("支持了rpc Multiply:", res.Pro)
	return nil
}

gdscript中使用如下步骤调用并获取返回值

var res = await gudpClient.RpcCall("Multiply",{"A":2,"B":3})
print(res)

Documentation

Index

Constants

View Source
const (
	HandshakeClientHelloRecordType byte = 1 << iota
	HandshakeHelloVerifyRecordType
	HandshakeServerHelloRecordType
	PingRecordType
	PongRecordType
	UnAuthenticated
)

Variables

View Source
var (
	ErrInvalidRecordType            = errors.New("invalid record type")
	ErrInsecureEncryptionKeySize    = errors.New("insecure encryption key size")
	ErrClientSessionNotFound        = errors.New("client session not found")
	ErrClientAddressIsNotRegistered = errors.New("client address is not registered")
	ErrClientNotFound               = errors.New("client not found")
	ErrMinimumPayloadSizeLimit      = errors.New("minimum payload size limit")
	ErrClientCookieIsInvalid        = errors.New("client cookie is invalid")
	ErrInvalidPayloadBodySize       = errors.New("payload body size is invalid")
)

custom error types

Functions

func CreateUdpAddr

func CreateUdpAddr(ip string, port int) (*net.UDPAddr, error)

func CreateUdpConn

func CreateUdpConn(host string, port int) *net.UDPConn

func ParseRecord

func ParseRecord(rec *[]byte) (gudp_protos.GudpMessageType, error)

parseRecord 解析消息返回对应的类型

Types

type AnyMessage

type AnyMessage struct {
	protoiface.MessageV1
	ReliableMessage   *gudp_protos.ReliableMessage
	UnreliableMessage *gudp_protos.UnreliableMessage
}

type AuthClient

type AuthClient interface {
	Authenticate(context.Context, []byte) (string, error)
}

An interface for authenticating the client token

type Client

type Client struct {
	ID string

	sync.Mutex
	// contains filtered or unexported fields
}

func (*Client) ValidateSessionID

func (c *Client) ValidateSessionID(sessionID []byte) bool

ValidateSessionID compares the client session ID with the given one

type ClientEvent

type ClientEvent struct {
	Name   ClientEventName `json:"name"`
	Client *Client         `json:"client"`
}

type ClientEventName

type ClientEventName int
const (
	ClientEventName_Client_Join ClientEventName = iota
	ClientEventName_Client_Leave
)

type DefaultAuthClient

type DefaultAuthClient struct{}

A simple implementation of auth client if no authentication is required

func (*DefaultAuthClient) Authenticate

func (a *DefaultAuthClient) Authenticate(context.Context, []byte) (string, error)

Only generates a new UUID for the user without any authentication

type HandlerFunc

type HandlerFunc func(client *Client, p []byte)

HandlerFunc is called when a custom message type is received from the client

type Option

type Option func(*Server)

func WithAsymmetricCrypto

func WithAsymmetricCrypto(ac crypto.Asymmetric) Option

WithAsymmetricCrypto sets the asymmetric cryptography implementation

func WithAuthClient

func WithAuthClient(ac AuthClient) Option

WithAuthClient sets the auth client implementation

func WithHeartbeatExpiration

func WithHeartbeatExpiration(t time.Duration) Option

WithHeartbeatExpiration sets the server heartbeat expiration option

func WithLogger

func WithLogger(l *log.Logger) Option

WithLogger sets the logger

func WithMinimumPayloadSize

func WithMinimumPayloadSize(i int) Option

WithMinimumPayloadSize sets the minimum payload size option

func WithProtosolVersion

func WithProtosolVersion(major, minor uint8) Option

WithProtosolVersion sets the server protosol version

func WithReadBufferSize

func WithReadBufferSize(i int) Option

WithReadBufferSize sets the read buffer size option

func WithSymmetricCrypto

func WithSymmetricCrypto(sc crypto.Symmetric) Option

WithSymmetricCrypto sets the symmetric cryptography implementation

func WithTranscoder

func WithTranscoder(t encoding.Transcoder) Option

WithTranscoder sets the transcoder implementation

type PacketData

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

type PacketQueue

type PacketQueue []PacketData

TODO: check if its better to have a slice of pointers to PacketData

func (*PacketQueue) Exists

func (pq *PacketQueue) Exists(sequence uint32) bool

func (*PacketQueue) InsertSorted

func (pq *PacketQueue) InsertSorted(p PacketData, maxSequence uint32)

type ReliabilitySystem

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

这些参数共同构成了可靠传输系统的核心部分,实现了数据包的确认、重传、丢失恢复和统计信息收集等功能。通过综合运用这些参数,系统能够保障数据包的可靠传输和相关的传输状态跟踪。 reliability system to support reliable connection

  • manages sent, received, pending ack and acked packet queues
  • separated out from reliable connection so they can be unit-tested

func NewReliabilitySystem

func NewReliabilitySystem(maxSequence uint32) *ReliabilitySystem

func (*ReliabilitySystem) AckedBandwidth

func (rs *ReliabilitySystem) AckedBandwidth() float64

func (*ReliabilitySystem) AckedPackets

func (rs *ReliabilitySystem) AckedPackets() uint32

func (*ReliabilitySystem) Acks

func (rs *ReliabilitySystem) Acks() []uint32

func (*ReliabilitySystem) GenerateAckBits

func (rs *ReliabilitySystem) GenerateAckBits() uint32

func (*ReliabilitySystem) HeaderSize

func (rs *ReliabilitySystem) HeaderSize() int

func (*ReliabilitySystem) LocalSequence

func (rs *ReliabilitySystem) LocalSequence() uint32

func (*ReliabilitySystem) LostPackets

func (rs *ReliabilitySystem) LostPackets() uint32

func (*ReliabilitySystem) MaxSequence

func (rs *ReliabilitySystem) MaxSequence() uint32

func (*ReliabilitySystem) PacketReceived

func (rs *ReliabilitySystem) PacketReceived(sequence uint32, size int)

func (*ReliabilitySystem) PacketSent

func (rs *ReliabilitySystem) PacketSent(size int)

验证收到的包

func (*ReliabilitySystem) ProcessAck

func (rs *ReliabilitySystem) ProcessAck(ack, ackBits uint32)

func (*ReliabilitySystem) ReceivedPackets

func (rs *ReliabilitySystem) ReceivedPackets() uint32

func (*ReliabilitySystem) RemoteSequence

func (rs *ReliabilitySystem) RemoteSequence() uint32

func (*ReliabilitySystem) Reset

func (rs *ReliabilitySystem) Reset()

func (*ReliabilitySystem) RoundTripTime

func (rs *ReliabilitySystem) RoundTripTime() time.Duration

func (*ReliabilitySystem) SentBandwidth

func (rs *ReliabilitySystem) SentBandwidth() float64

func (*ReliabilitySystem) SentPackets

func (rs *ReliabilitySystem) SentPackets() uint32

func (*ReliabilitySystem) Update

func (rs *ReliabilitySystem) Update(deltaTime time.Duration)

type Rpc

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

func NewRpc

func NewRpc(rcvr any) (*Rpc, error)

func (*Rpc) Call

func (s *Rpc) Call(ctx context.Context, mtype *methodType, argv, replyv reflect.Value) error

func (*Rpc) ParseRequestRpc

func (s *Rpc) ParseRequestRpc(req *gudp_protos.RpcMessage) (*methodType, reflect.Value, reflect.Value, error)

通过rpc消息解析调用引用类型

type Server

type Server struct {
	Error chan error // 当服务出现错误
	// contains filtered or unexported fields
}

func NewServerManager

func NewServerManager(conn *net.UDPConn, options ...Option) (*Server, error)

func (*Server) FindClientByAddr

func (s *Server) FindClientByAddr(addr *net.UDPAddr) (*Client, bool)

returns the Client by IP & Port

func (*Server) RegisterEvent

func (s *Server) RegisterEvent(eventFunc func(*ClientEvent))

func (*Server) RegisterRpc

func (s *Server) RegisterRpc(rcvr any)

注册rpc

func (*Server) SendClientMessage

func (s *Server) SendClientMessage(cli *Client, bytes []byte, reliability bool) error

将消息发送到指定地址

func (*Server) SendMessage

func (s *Server) SendMessage(addr *net.UDPAddr, bytes []byte, reliability bool) error

将消息发送到指定地址

func (*Server) Serve

func (s *Server) Serve()

Serve starts listening to the UDP port for incoming bytes & then sends payload and sender address into the rawRecords channel if no error is found

func (*Server) SetHandler

func (s *Server) SetHandler(f HandlerFunc)

SetHandler sets the handler function as a callback to call when a custom record type is received from the client

Directories

Path Synopsis
pb

Jump to

Keyboard shortcuts

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