socketio

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

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

Go to latest
Published: Jul 8, 2015 License: BSD-3-Clause Imports: 19 Imported by: 0

README

##socket.io library for Golang

Branch master branch is compatible with socket.io 0.9.x. For latest version, please check branch 1.0.

forked from http://code.google.com/p/go-socketio Documentation: http://godoc.org/github.com/googollee/go-socket.io ##Demo

server: //example/server/app.go

package main

import (
	"runtime"
	//"io/ioutil"
	"encoding/json"
	"github.com/xjtdy888/go-socket.io"
	"log"
	"net/http"
	_ "net/http/pprof"
	//"strings"
)


func main() {
	log.SetFlags(log.LstdFlags|log.Lshortfile)
	//log.SetOutput(ioutil.Discard)
	sio := socketio.NewSocketIOServer(&socketio.Config{})
	//sio.Config.NameSpace = "/tbim-1/1/"

	// Set the on connect handler
	sio.On("connect", func(ns *socketio.NameSpace) {
		log.Println("Connected: ", ns.Id())
		sio.Broadcast("connected", ns.Id())
	})

	// Set the on disconnect handler
	sio.On("disconnect", func(ns *socketio.NameSpace) {
		log.Println("Disconnected: ", ns.Id())
		sio.Broadcast("disconnected", ns.Id())
	})

	// Set a handler for news messages
	sio.On("news", func(ns *socketio.NameSpace, message string) {
		sio.Broadcast("news", message)
	})

	// Set a handler for ping messages
	sio.On("ping", func(ns *socketio.NameSpace) {
		ns.Emit("pong", nil)
	})

	// Set an on connect handler for the pol channel
	sio.Of("/pol").On("connect", func(ns *socketio.NameSpace) {
		log.Println("Pol Connected: ", ns.Id())
	})

	// We can broadcast messages. Set a handler for news messages from the pol
	// channel
	sio.Of("/pol").On("news", func(ns *socketio.NameSpace, message string) {
		sio.In("/pol").Broadcast("news", message)
	})

	// And respond to messages! Set a handler with a response for poll messages
	// on the pol channel
	sio.Of("/pol").On("poll", func(ns *socketio.NameSpace, message string) bool {
		if strings.Contains(message, "Nixon") {
			return true
		}

		return false
	})

	// Set an on disconnect handler for the pol channel
	sio.Of("/pol").On("disconnect", func(ns *socketio.NameSpace) {
		log.Println("Pol Disconnected: ", ns.Id())
	})

	// Serve our website
	sio.Handle("/", http.FileServer(http.Dir("./www/")))


	sio.HandleFunc("/stats", func(w http.ResponseWriter, r *http.Request){
		stats := sio.Stats.Dump()
		data, err := json.Marshal(stats)
		if err != nil {
			return 
		}
		w.Write(data)
		runtime.GC()
	})
	
	go func() {
	        log.Println(http.ListenAndServe(":6060", nil)) 
	
	}()
	

	// Start listening for socket.io connections
	log.Println("listening on port 3000")
	log.Fatal(http.ListenAndServe(":3000", sio))
}

##Changelog

  • Added a socket.io client for quick use
  • Fixed the disconnect event
  • Added persistent sessionIds
  • Added session values
  • Added broadcast
  • Added a simpler Emit function to namespaces
  • Fixed connected event on endpoints
  • Added events without arguments
  • Added Polling Transport

Documentation

Index

Constants

View Source
const (
	PACKET_DISCONNECT = iota
	PACKET_CONNECT
	PACKET_HEARTBEAT
	PACKET_MESSAGE
	PACKET_JSONMESSAGE
	PACKET_EVENT
	PACKET_ACK
	PACKET_ERROR
	PACKET_NOOP
)
View Source
const (
	SessionIDLength  = 32
	SessionIDCharset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)

Variables

View Source
var ClosingError = errors.New("Handler Closing")
View Source
var (
	DefaultTransports = NewTransportManager()
)
View Source
var NotConnected = errors.New("not connected")

Functions

func NewSessionID

func NewSessionID() string

func StackTrace

func StackTrace(all bool) string

Types

type Broadcaster

type Broadcaster struct {
	Namespaces []*NameSpace
}

func (*Broadcaster) Broadcast

func (b *Broadcaster) Broadcast(name string, args ...interface{})

func (*Broadcaster) Except

func (b *Broadcaster) Except(namespace *NameSpace) *Broadcaster

type Config

type Config struct {
	ResourceName         string //命名空间
	HeartbeatInterval    int    //心跳时间
	SessionExpiry        int    //session 有效时间
	SessionCheckInterval int    //session 检查间隔
	PollingTimeout       int    //polling 超时时间
	ClosingTimeout       int
	NewSessionID         func() string
	Transports           *TransportManager
	Authorize            func(*http.Request, map[interface{}]interface{}) bool
}

type Event

type Event struct {
	Name string          `json:"name"`
	Args json.RawMessage `json:"args"`
}

type EventEmitter

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

func NewEventEmitter

func NewEventEmitter() *EventEmitter

func (*EventEmitter) On

func (ee *EventEmitter) On(name string, fn interface{}) error

func (*EventEmitter) RemoveAllListeners

func (ee *EventEmitter) RemoveAllListeners(name string)

func (*EventEmitter) RemoveListener

func (ee *EventEmitter) RemoveListener(name string, fn interface{})

type MessageType

type MessageType uint8

type MovingAverage

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

func NewMovingAverage

func NewMovingAverage(period int) *MovingAverage

type NameSpace

type NameSpace struct {
	*EventEmitter

	Session *Session
	// contains filtered or unexported fields
}

func NewNameSpace

func NewNameSpace(session *Session, endpoint string, ee *EventEmitter) *NameSpace

func (*NameSpace) Call

func (ns *NameSpace) Call(name string, timeout time.Duration, reply []interface{}, args ...interface{}) error

func (*NameSpace) Emit

func (ns *NameSpace) Emit(name string, args ...interface{}) error

func (*NameSpace) Endpoint

func (ns *NameSpace) Endpoint() string

func (*NameSpace) Id

func (ns *NameSpace) Id() string

func (*NameSpace) Send

func (ns *NameSpace) Send(message interface{}) error

type Packet

type Packet interface {
	Id() int
	Type() MessageType
	EndPoint() string
	Ack() bool
}

type Session

type Session struct {
	sync.Mutex
	SessionId string

	Values  map[interface{}]interface{}
	Request *http.Request

	SendBuffer [][]byte
	// contains filtered or unexported fields
}

func NewSession

func NewSession(sessionId string, srv *SocketIOServer, r *http.Request) *Session

func (*Session) Close

func (ss *Session) Close(params ...interface{}) error

func (*Session) Closed

func (ss *Session) Closed() bool

func (*Session) Flush

func (ss *Session) Flush() error

func (*Session) Less

func (ss *Session) Less(b *Session) bool

func (*Session) Of

func (ss *Session) Of(name string) (nameSpace *NameSpace)

func (*Session) RawMessage

func (ss *Session) RawMessage(msg []byte) error

func (*Session) RemoveHandler

func (ss *Session) RemoveHandler(h SessionHandler) bool

func (*Session) Send

func (ss *Session) Send(data []byte) error

func (*Session) SetHandler

func (ss *Session) SetHandler(h SessionHandler) bool

type SessionContainer

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

func NewSessionContainer

func NewSessionContainer() *SessionContainer

func (*SessionContainer) Add

func (s *SessionContainer) Add(ss *Session)

func (*SessionContainer) Expire

func (s *SessionContainer) Expire()

func (*SessionContainer) Get

func (s *SessionContainer) Get(sessionId string) *Session

func (*SessionContainer) Range

func (s *SessionContainer) Range() map[string]*Session

func (*SessionContainer) Remove

func (s *SessionContainer) Remove(ss *Session)

type SessionHandler

type SessionHandler interface {
	SendMessage(data []byte) error
}

type SocketIOServer

type SocketIOServer struct {
	*http.ServeMux

	Config *Config
	Stats  *StatsCollector
	// contains filtered or unexported fields
}

func NewSocketIOServer

func NewSocketIOServer(config *Config) *SocketIOServer

func (*SocketIOServer) Broadcast

func (srv *SocketIOServer) Broadcast(name string, args ...interface{})

func (*SocketIOServer) Except

func (srv *SocketIOServer) Except(ns *NameSpace) *Broadcaster

func (*SocketIOServer) In

func (srv *SocketIOServer) In(name string) *Broadcaster

func (*SocketIOServer) Of

func (srv *SocketIOServer) Of(name string) *EventEmitter

func (*SocketIOServer) On

func (srv *SocketIOServer) On(name string, fn interface{}) error

func (*SocketIOServer) RemoveAllListeners

func (srv *SocketIOServer) RemoveAllListeners(name string)

func (*SocketIOServer) RemoveListener

func (srv *SocketIOServer) RemoveListener(name string, fn interface{})

func (*SocketIOServer) ServeHTTP

func (srv *SocketIOServer) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*SocketIOServer) Sessions

func (srv *SocketIOServer) Sessions() *SessionContainer

type StatsCollector

type StatsCollector struct {
	StartTime time.Time

	MaxSession    int64
	ActiveSession int64

	MaxConnections    float64
	ActiveConnections float64
	ConnectionsPs     *MovingAverage

	PacketsSentPs *MovingAverage
	PacketsRecvPs *MovingAverage
	// contains filtered or unexported fields
}

func NewStatsCollector

func NewStatsCollector() *StatsCollector

func (*StatsCollector) ConnectionClosed

func (s *StatsCollector) ConnectionClosed()

func (*StatsCollector) ConnectionOpened

func (s *StatsCollector) ConnectionOpened()

func (*StatsCollector) Dump

func (s *StatsCollector) Dump() *StatsResult

func (*StatsCollector) OnPacketRecv

func (s *StatsCollector) OnPacketRecv(num int)

func (*StatsCollector) OnPacketSent

func (s *StatsCollector) OnPacketSent(num int)

func (*StatsCollector) SessionClosed

func (s *StatsCollector) SessionClosed()

func (*StatsCollector) SessionOpened

func (s *StatsCollector) SessionOpened()

func (*StatsCollector) Start

func (s *StatsCollector) Start()

type StatsResult

type StatsResult struct {
	StartTime     time.Time
	MaxSession    int64
	ActiveSession int64

	MaxConnections    float64
	ActiveConnections float64

	ConnectionsPs float64

	PacketsSentPs float64
	PacketsRecvPs float64
}

type Transport

type Transport interface {
	Send([]byte) error
	Read() (io.Reader, error)
}

type TransportManager

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

func NewTransportManager

func NewTransportManager() *TransportManager

func (*TransportManager) GetTransportNames

func (tm *TransportManager) GetTransportNames() (names []string)

func (*TransportManager) RegisterTransport

func (tm *TransportManager) RegisterTransport(name string)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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