socketio

package module
v0.0.0-...-263540a Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2014 License: BSD-3-Clause Imports: 18 Imported by: 0

README

##socket.io library for Golang

forked from http://code.google.com/p/go-socketio

##Demo

server:

package main

import (
  "fmt"
  "github.com/googollee/go-socket.io"
  "log"
  "net/http"
  "time"
)

func news(ns *socketio.NameSpace, title, body string, article_num int) {
  var name string
  name = ns.Session.Values["name"].(string)
  fmt.Printf("%s said in %s, title: %s, body: %s, article number: %i", name, ns.Endpoint(), title, body, article_num)
}

func onConnect(ns *socketio.NameSpace) {
  fmt.Println("connected:", ns.Id(), " in channel ", ns.Endpoint())
  ns.Session.Values["name"] = "this guy"
  ns.Emit("news", "this is totally news", 3)
}

func onDisconnect(ns *socketio.NameSpace) {
  fmt.Println("disconnected:", ns.Id(), " in channel ", ns.Endpoint())
}

func main() {
  sock_config := &socketio.Config{}
  sock_config.HeartbeatTimeout = 2
  sock_config.ClosingTimeout = 4

  sio := socketio.NewSocketIOServer(sock_config)

  // Handler for new connections, also adds socket.io event handlers
  sio.On("connect", onConnect)
  sio.On("disconnect", onDisconnect)
  sio.On("news", news)
  sio.On("ping", func(ns *socketio.NameSpace){
    sio.Broadcast("pong", nil)
  })

  //in politics channel
  sio.Of("/pol").On("connect", onConnect)
  sio.Of("/pol").On("disconnect", onDisconnect)
  sio.Of("/pol").On("news", news)
  sio.Of("/pol").On("ping", func(ns *socketio.NameSpace){
    sio.In("/pol").Broadcast("pong", nil)
  })

  //this will serve a http static file server
  sio.Handle("/", http.FileServer(http.Dir("./public/")))
  //startup the server
  log.Fatal(http.ListenAndServe(":3000", sio))
}

go client:

package main

import (
  "log"
  "github.com/googollee/go-socket.io"
)

func pol() {
  client, err := socketio.Dial("http://127.0.0.1:3000/pol")
  if err != nil {
    panic(err)
  }
  client.On("connect", func(ns *socketio.NameSpace) {
    log.Println("pol connected")
  })
  client.On("news", func(ns *socketio.NameSpace, message string) {
    log.Println(message, " in Pol")
  })
  client.Run()
}

func main() {
  client, err := socketio.Dial("http://127.0.0.1:3000/")
  if err != nil {
    panic(err)
  }
  client.On("connect", func(ns *socketio.NameSpace) {
    log.Println("connected")
    ns.Emit("ping", nil)
  })
  client.Of("/pol").On("news", func(ns *socketio.NameSpace, message string) {
    log.Println(message, " in Pol 2")
  })
  client.On("news", func(ns *socketio.NameSpace, message string) {
    log.Println(message)
  })
  client.On("pong", func(ns *socketio.NameSpace) {
    log.Println("got pong")
  })

  go pol()

  client.Run()
}

javascript client

NOTE: There is a provided socket.io.js file in the lib folder for including in your project

  var socket = io.connect();
  socket.on("connect", function(){
    socket.emit("news", "this is title", "this is body", 1)
  })
  socket.on("news", function(message, urgency){
    console.log(message + urgency);
    socket.emit("ping")
  })
  socket.on("pong", function() {
    console.log("got pong")
  })
  socket.of("/pol").on("news", function(message, urgency){
    console.log(message + urgency);
    socket.emit("ping")
  })
  socket.of("/pol").on("pong", function() {
    console.log("got pong")
  })
  socket.on("disconnect", function() {
    alert("You have disconnected from the server")
  })
  var pol = io.connect("http://localhost/pol");
  pol.on("pong", function() {
    console.log("got pong from pol")
  })
  pol.on("news", function(message, urgency){
    console.log(message + urgency);
    socket.emit("ping")
  })

##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
  • Fixed go client endpoints

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  = 16
	SessionIDCharset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
)
View Source
const (
	ProtocolVersion = 1
)

Variables

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

Functions

func NewSessionID

func NewSessionID() 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 Client

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

func Dial

func Dial(origin string) (*Client, error)

func (*Client) Call

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

func (*Client) Emit

func (c *Client) Emit(name string, args ...interface{}) error

func (*Client) Of

func (c *Client) Of(name string) (nameSpace *NameSpace)

func (*Client) Quit

func (c *Client) Quit() error

func (*Client) Run

func (c *Client) Run()

type Config

type Config struct {
	HeartbeatTimeout int
	ClosingTimeout   int
	NewSessionID     func() string
	Transports       *TransportManager
	Authorize        func(*http.Request) 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 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

type Packet

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

type Session

type Session struct {
	SessionId string

	Values map[interface{}]interface{}
	// contains filtered or unexported fields
}

func NewSession

func NewSession(emitters map[string]*EventEmitter, sessionId string, timeout int, sendHeartbeat bool) *Session

func (*Session) Of

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

type SocketIOServer

type SocketIOServer struct {
	*http.ServeMux
	// 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)

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