gwork

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

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

Go to latest
Published: Sep 4, 2020 License: MIT Imports: 16 Imported by: 0

README

线上demo

聊天室: http://www.24dota.com:8001/chat

小蝌蚪游戏: http://www.24dota.com:8006/demo/ 多人同屏,基于范围推送

小蝌蚪项目地址 https://github.com/ManiacMike/go_websocket_chatroom

特性

  • 高性能的golang websocket 服务器框架
  • 支持全局推送,room推送和基于geohash的虚拟地图推送(可用于mmorpg游戏)三种推送方式
  • 如果你使用golang,简单就可以实现一个websocket聊天室服务器
package main

import (
	"fmt"
	"github.com/ManiacMike/gwork"
	"time"
)

func main() {
  //设置新建用户连接的callback
	gwork.SetGetConnCallback(func(uid string, room *gwork.Room) {
		welcome := map[string]interface{}{
			"type":       "user_count",
			"user_count": len(room.Userlist),
		}
		room.Broadcast(welcome)
	})

  //设置丢失用户连接的callback
	gwork.SetLoseConnCallback(func(uid string, room *gwork.Room) {
		close := map[string]interface{}{
			"type":       "user_count",
			"user_count": len(room.Userlist),
		}
		room.Broadcast(close)
	})

  //设置处理客户端请求的方法
	gwork.SetRequestHandler(func(receiveNodes map[string]interface{}, uid string, room *gwork.Room) {
		reply := map[string]interface{}{
			"type":    "message",
			"content": receiveNodes["content"].(string),
			"uname":   receiveNodes["uname"].(string),
			"time":    time.Now().Unix(),
		}
		room.Broadcast(reply)
	})

  //读取配置,启动日志,stats,网络监听
	gwork.Start()
}

  • 如果你使用其他的后端语言,请使用gateway的demo
  • 简单的服务器状态信息 8011是在配置文件中配置的admin port
Mikes-iMac:~ Mike$ telnet 127.0.0.1 8011
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
stats
===============================
Version: 0.1.0
Uptime: 2 minutes, 19 seconds
Copyright (c) 2016 gwork
*******************************
config:
ServerPort:          8001
LogLevel:            INFO
usage:
Current User Num:    1
Current Room Num:    1
Peak User Num:       1
Peak Room Num:       1
===============================
quit

配置及安装

在你的项目下新建config.ini文件

[server]
#必须参数
port = 8001

[websocket]
#必须参数,设置uid的参数名
uid_name = uid
#必选参数 1全局广播 2按房间广播 3按地理位置广播
broad_type = 1
#可选参数,默认room_id。设置room id的参数名
#rid_name = room_id
#可选参数,默认1(get),可选2(cookie)。设置读取uid和rid的方式
param_type = 2

[log]
#可选参数
log_queue_size = 1000
#可选参数
log_buffer_size = 2
#可选参数
log_level = 1

[admin]
#必须参数
port = 8011

go run main.go

Documentation

Index

Constants

View Source
const (
	WsParamTypeGet    = 1
	WsParamTypeCookie = 2
)
View Source
const (
	LogLevelDebug = iota
	LogLevelInfo
	LogLevelNotice
	LogLevelWarning
	LogLevelError
)

defined log levels

View Source
const (
	StatsCmdNewUser = iota
	StatsCmdLostUser
	StatsCmdNewRoom
	StatsCmdCloseRoom
	StatsCmdReport
)
View Source
const (
	WsBroadTypeAll  = 1
	WsBroadTypeRoom = 2
	WsBroadTypeMap  = 3
)
View Source
const (
	BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"
)

map 64800

View Source
const (
	Version = "0.1.0"
)

Variables

View Source
var GenerateUid func() string
View Source
var GetConnCallback func(string, *Room)
View Source
var HandleRequest func(map[string]interface{}, string, *Room)
View Source
var LoseConnCallback func(string, *Room)

Functions

func CheckErr

func CheckErr(err error)

func Error

func Error(msg string) error

func FlushLog

func FlushLog()

func GenerateUnixNanoId

func GenerateUnixNanoId() string

func GetConfig

func GetConfig(configFile string, sec string) (map[string]string, error)

func JsonDecode

func JsonDecode(jsonStr string) interface{}

func JsonEncode

func JsonEncode(nodes interface{}) string

func LoadConfig

func LoadConfig(section string) map[string]string

func Log

func Log(level LogLevel, a ...interface{})

func Logf

func Logf(level LogLevel, format string, a ...interface{})

func SendStats

func SendStats(cmdCode int) (replyChan chan string)

Send status command to status server

func SetGenerateUid

func SetGenerateUid(f func() string)

func SetGetConnCallback

func SetGetConnCallback(f func(string, *Room))

func SetLoseConnCallback

func SetLoseConnCallback(f func(string, *Room))

func SetRequestHandler

func SetRequestHandler(f func(map[string]interface{}, string, *Room))

func Start

func Start()

func StatsReport

func StatsReport() string

func UptimeFormat

func UptimeFormat(secs uint32, section int) string

func WsServer

func WsServer(ws *websocket.Conn)

Types

type Box

type Box struct {
	MinX, MaxX int
	MinY, MaxY int
}

func (*Box) Height

func (this *Box) Height() int

func (*Box) Width

func (this *Box) Width() int

type ConfigType

type ConfigType struct {
	ServerPort    string
	WsUidName     string
	WsBroadType   uint
	WsRidName     string
	WsParamType   uint
	WsTlsEnable   uint
	WsTlsCrt      string
	WsTlsKey      string
	LogQueueSize  uint
	LogBufferSize uint16
	LogLevel      LogLevel
	AdminPort     string
}

type CoordNode

type CoordNode struct {
	Geohash string
	// contains filtered or unexported fields
}

type LogLevel

type LogLevel uint8

type MapType

type MapType struct {
	Lock *sync.Mutex
	// contains filtered or unexported fields
}

func NewMap

func NewMap(width int, height int) *MapType

创建全局的map

func (*MapType) AddCoord

func (this *MapType) AddCoord(key string, x, y int)

func (*MapType) AddCoordNode

func (this *MapType) AddCoordNode(key string, coordNode *CoordNode)

增加key的坐标节点

func (*MapType) DeleteCoordNode

func (this *MapType) DeleteCoordNode(key string) bool

删除key的坐标节点

func (*MapType) Encode

func (this *MapType) Encode(x, y int) (string, *Box)

func (*MapType) GetAllCoordNodes

func (this *MapType) GetAllCoordNodes() map[string]*CoordNode

func (*MapType) GetCoordNode

func (this *MapType) GetCoordNode(key string) (*CoordNode, bool)

得到key的坐标节点

func (*MapType) GetNeighbors

func (this *MapType) GetNeighbors(x, y int) []string

func (*MapType) NewCoordNode

func (this *MapType) NewCoordNode(x, y int) *CoordNode

func (*MapType) QueryNearestSquare

func (this *MapType) QueryNearestSquare(x, y int) []string

查找(x, y)附近(九宫格内)的节点,返回它们的key

func (*MapType) QueryNearestSquareFromKey

func (this *MapType) QueryNearestSquareFromKey(key string) []string

查找key附近(九宫格内)的节点,返回他们的key

func (*MapType) UpdateCoord

func (this *MapType) UpdateCoord(key string, newx, newy int) bool

func (*MapType) UpdateCoordNode

func (this *MapType) UpdateCoordNode(key string, coordNode *CoordNode) bool

更新key的坐标节点

type Room

type Room struct {
	RoomId   string
	Userlist []User
}

func NewRoom

func NewRoom(roomId string) *Room

func (*Room) Broadcast

func (room *Room) Broadcast(replyBody map[string]interface{}) error

func (*Room) ChangeConn

func (room *Room) ChangeConn(index int, con *websocket.Conn)

func (*Room) ExistUser

func (room *Room) ExistUser(uid string) (bool, int)

func (*Room) NewUser

func (room *Room) NewUser(ws *websocket.Conn, uid string) string

func (*Room) Push

func (room *Room) Push(user User, replyBody map[string]interface{}) error

func (*Room) PushByUid

func (room *Room) PushByUid(uid string, replyBody map[string]interface{}) error

func (*Room) PushUserCount

func (room *Room) PushUserCount(event string, uid string)

func (*Room) RemoveUser

func (room *Room) RemoveUser(uid string)

type ServerStats

type ServerStats struct {
	UserCurrent uint
	UserPeak    uint
	RoomCurrent uint
	RoomPeak    uint
	Version     string
	StartTime   time.Time
}

func (*ServerStats) HandleCommand

func (stats *ServerStats) HandleCommand(cmd statsCmd) error

func (*ServerStats) Report

func (stats *ServerStats) Report() string

type ServiceError

type ServiceError struct {
	Msg string
}

func (*ServiceError) Error

func (e *ServiceError) Error() string

type User

type User struct {
	Uid string
	Con *websocket.Conn
}

type UserList

type UserList []User

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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