socketio

package module
v1.4.6-0...-207f66d Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2019 License: BSD-3-Clause Imports: 11 Imported by: 1

README

go-socket.io

GoDoc Build Status

Coverage Status

Go Report Card

go-socket.io is an implementation of Socket.IO in Golang, which is a realtime application framework.

Currently this library supports 1.4 version of the Socket.IO client. It supports room and namespaces.

Go 1.9+ is required!

Help wanted This project is looking for contributors to help fix bugs and implement new features. Please check Issue 192. All help is much appreciated.

  • for compatibility with Socket.IO 0.9.x, please use branch 0.9.x *

Contents

Install

Install the package with:

go get github.com/googollee/go-socket.io

Import it with:

import "github.com/googollee/go-socket.io"

and use socketio as the package name inside the code.

Last changes

Important changes:

Short info Description Date
Changed signature of OnError Changed signature of OnError From: server.OnError(string, func(error)) To: server.OnError(string, func(Conn, error)) 2019-10-16

Example

Please check the example folder for details.

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/googollee/go-socket.io"
)

func main() {
	server, err := socketio.NewServer(nil)
	if err != nil {
		log.Fatal(err)
	}
	server.OnConnect("/", func(s socketio.Conn) error {
		s.SetContext("")
		fmt.Println("connected:", s.ID())
		return nil
	})
	server.OnEvent("/", "notice", func(s socketio.Conn, msg string) {
		fmt.Println("notice:", msg)
		s.Emit("reply", "have "+msg)
	})
	server.OnEvent("/chat", "msg", func(s socketio.Conn, msg string) string {
		s.SetContext(msg)
		return "recv " + msg
	})
	server.OnEvent("/", "bye", func(s socketio.Conn) string {
		last := s.Context().(string)
		s.Emit("bye", last)
		s.Close()
		return last
	})
	server.OnError("/", func(s socketio.Conn, e error) {
		fmt.Println("meet error:", e)
	})
	server.OnDisconnect("/", func(s socketio.Conn, reason string) {
		fmt.Println("closed", reason)
	})
	go server.Serve()
	defer server.Close()

	http.Handle("/socket.io/", server)
	http.Handle("/", http.FileServer(http.Dir("./asset")))
	log.Println("Serving at localhost:8000...")
	log.Fatal(http.ListenAndServe(":8000", nil))
}

Acknowledgements in go-socket.io 1.X.X

See documentation about acknowledgements

Sending ACK with data from SERVER to CLIENT
  • Client-side
 //using client-side socket.io-1.X.X.js
 socket.emit('some:event', JSON.stringify(someData), function(data){
       console.log('ACK from server wtih data: ', data));
 });
  • Server-side
// The return type may vary depending on whether you will return
// In golang implementation of Socket.IO don't used callbacks for acknowledgement,
// but used return value, which wrapped into ack package and returned to the client's callback in JavaScript
so.On("some:event", func(msg string) string {
	return msg //Sending ack with data in msg back to client, using "return statement"
})
Sending ACK with data from CLIENT to SERVER
  • Client-side
//using client-side socket.io-1.X.X.js
//last parameter of "on" handler is callback for sending ack to server with data or without data
socket.on('some:event', function (msg, sendAckCb) {
    //Sending ACK with data to server after receiving some:event from server
    sendAckCb(JSON.stringify(data)); // for example used serializing to JSON
}
  • Server-side
//You can use Emit or BroadcastTo with last parameter as callback for handling ack from client
//Sending packet to room "room_name" and event "some:event"
so.BroadcastTo("room_name", "some:event", dataForClient, func (so socketio.Socket, data string) {
	log.Println("Client ACK with data: ", data)
})

// Or

so.Emit("some:event", dataForClient, func (so socketio.Socket, data string) {
	log.Println("Client ACK with data: ", data)
})
Cautch Disconnected reason
  • Server-side

so.OnDisconnect("/", func(so socketio.Conn, reason string) {
  	log.Println("closed", reason)
})

Possible reasons:

Reason Side Description
client namespace disconnect Client Side Got disconnect packet from client

Community

Telegram chat: @go_socketio

Contributors

This project exists thanks to all the people who contribute. [Contribute].

License

The 3-clause BSD License - see LICENSE for more details

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Broadcast

type Broadcast interface {
	Join(room string, connection Conn)            // Join causes the connection to join a room
	Leave(room string, connection Conn)           // Leave causes the connection to leave a room
	LeaveAll(connection Conn)                     // LeaveAll causes given connection to leave all rooms
	Clear(room string)                            // Clear causes removal of all connections from the room
	Send(room, event string, args ...interface{}) // Send will send an event with args to the room
	SendAll(event string, args ...interface{})    // SendAll will send an event with args to all the rooms
	Len(room string) int                          // Len gives number of connections in the room
	Rooms(connection Conn) []string               // Gives list of all the rooms if no connection given, else list of all the rooms the connection joined
}

Broadcast is the adaptor to handle broadcasts & rooms for socket.io server API

func NewBroadcast

func NewBroadcast() Broadcast

NewBroadcast creates a new broadcast adapter

type Conn

type Conn interface {
	// ID returns session id
	ID() string
	Close() error
	URL() url.URL
	LocalAddr() net.Addr
	RemoteAddr() net.Addr
	RemoteHeader() http.Header

	// Context of this connection. You can save one context for one
	// connection, and share it between all handlers. The handlers
	// is called in one goroutine, so no need to lock context if it
	// only be accessed in one connection.
	Context() interface{}
	SetContext(v interface{})
	Namespace() string
	Emit(msg string, v ...interface{})

	// Broadcast server side apis
	Join(room string)
	Leave(room string)
	LeaveAll()
	Rooms() []string
}

Conn is a connection in go-socket.io

type Server

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

Server is a go-socket.io server.

func NewServer

func NewServer(c *engineio.Options) (*Server, error)

NewServer returns a server.

func (*Server) BroadcastToRoom

func (s *Server) BroadcastToRoom(room, event string, args ...interface{})

BroadcastToRoom broadcasts given event & args to all the connections in the room

func (*Server) ClearRoom

func (s *Server) ClearRoom(room string)

ClearRoom clears the room

func (*Server) Close

func (s *Server) Close() error

Close closes server.

func (*Server) JoinRoom

func (s *Server) JoinRoom(room string, connection Conn)

JoinRoom joins given connection to the room

func (*Server) LeaveAllRooms

func (s *Server) LeaveAllRooms(connection Conn)

LeaveAllRooms leaves the given connection from all rooms

func (*Server) LeaveRoom

func (s *Server) LeaveRoom(room string, connection Conn)

LeaveRoom leaves given connection from the room

func (*Server) OnConnect

func (s *Server) OnConnect(nsp string, f func(Conn) error)

OnConnect set a handler function f to handle open event for namespace nsp.

func (*Server) OnDisconnect

func (s *Server) OnDisconnect(nsp string, f func(Conn, string))

OnDisconnect set a handler function f to handle disconnect event for namespace nsp.

func (*Server) OnError

func (s *Server) OnError(nsp string, f func(Conn, error))

OnError set a handler function f to handle error for namespace nsp.

func (*Server) OnEvent

func (s *Server) OnEvent(nsp, event string, f interface{})

OnEvent set a handler function f to handle event for namespace nsp.

func (*Server) RoomLen

func (s *Server) RoomLen(room string) int

RoomLen gives number of connections in the room

func (*Server) Rooms

func (s *Server) Rooms() []string

Rooms gives list of all the rooms

func (*Server) Serve

func (s *Server) Serve() error

Serve serves go-socket.io server

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)

Directories

Path Synopsis
example
iris Module

Jump to

Keyboard shortcuts

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