socketio

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

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

Go to latest
Published: Nov 13, 2020 License: BSD-3-Clause Imports: 16 Imported by: 0

README

socketio

A copy of github.com/googollee/go-socket.io renamed with defects fixed and updated to 1.4.5 of socket.io. Also works with 1.7.4 and 2.0.3 of Socket.IO client Javascript.

socketio is an implementation of socket.io in Go (golang). This provides the ability to perform real time communication from a browser to a server and back. Content can be pushed from the server out to the browser.

It is compatible with the 1.4.5 version of socket.io in Node.js, and supports room and namespace. This version will be updated on a regular basis with the latest version of socket.io.

Install

Install the package with:

	go get github.com/mlsquires/socketio
	go get github.com/pschlump/godebug
	go get github.com/pschlump/MiscLib

Import it with:

	import "github.com/mlsquires/socketio"

Example

Please check the ./examples/chat directory for more comprehensive examples.

	package main

	//
	// Command line arguments can be used to set the IP address that is listened to and the port.
	//
	// $ ./chat --port=8080 --host=127.0.0.1
	//
	// Bring up a pair of browsers and chat between them.
	//

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

		"github.com/pschlump/MiscLib"
		"github.com/pschlump/godebug"
		"github.com/mlsquires/socketio"
	)

	var Port = flag.String("port", "9000", "Port to listen to")                           // 0
	var HostIP = flag.String("host", "localhost", "Host name or IP address to listen on") // 1
	var Dir = flag.String("dir", "./asset", "Direcotry where files are served from")      // 1
	func init() {
		flag.StringVar(Port, "P", "9000", "Port to listen to")                           // 0
		flag.StringVar(HostIP, "H", "localhost", "Host name or IP address to listen on") // 1
		flag.StringVar(Dir, "d", "./asset", "Direcotry where files are served from")     // 1
	}

	func main() {

		flag.Parse()
		fns := flag.Args()

		if len(fns) != 0 {
			fmt.Printf("Usage: Invalid arguments supplied, %s\n", fns)
			os.Exit(1)
		}

		var host_ip string = ""
		if *HostIP != "localhost" {
			host_ip = *HostIP
		}

		// Make certain that the command line parameters are handled correctly
		// fmt.Printf("host_ip >%s< HostIP >%s< Port >%s<\n", host_ip, *HostIP, *Port)

		server, err := socketio.NewServer(nil)
		if err != nil {
			log.Fatal(err)
		}

		server.On("connection", func(so socketio.Socket) {
			fmt.Printf("%sa user connected%s, %s\n", MiscLib.ColorGreen, MiscLib.ColorReset, godebug.LF())
			so.Join("chat")
			so.On("chat message", func(msg string) {
				fmt.Printf("%schat message, %s%s, %s\n", MiscLib.ColorGreen, msg, MiscLib.ColorReset, godebug.LF())
				so.BroadcastTo("chat", "chat message", msg)
			})
			so.On("disconnect", func() {
				fmt.Printf("%suser disconnect%s, %s\n", MiscLib.ColorYellow, MiscLib.ColorReset, godebug.LF())
			})
		})

		server.On("error", func(so socketio.Socket, err error) {
			fmt.Printf("Error: %s, %s\n", err, godebug.LF())
		})

		http.Handle("/socket.io/", server)
		http.Handle("/", http.FileServer(http.Dir(*Dir)))
		fmt.Printf("Serving on port %s, brows to http://localhost:%s/\n", *Port, *Port)
		listen := fmt.Sprintf("%s:%s", host_ip, *Port)
		log.Fatal(http.ListenAndServe(listen, nil))
	}

License

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

History

This code is from an original https://github.com/googollee/go-socket.io . The following have been made:

  1. Renamed the package so that the directory structure matches with the package name. Some outside tools depend on this.
  2. Included go-engine.io as a subdirectory.
  3. Fixed defect #68 - "Not Thread Safe". All accesses to maps are synchronized.
  4. Documentation improvements.
  5. Updated to use the current version of socket.io (1.3.6)
  6. Provided a packed(uglified) version of the JavaScript scoket.io library. A non-uglified version is in the same directory also.
  7. Original defect #95 - Crash occurs when too many arguments are passed - suggested fix used and tested.
  8. Fixed a set of continuous connect/disconnect problems
  9. #45 - incorrect usage - see correct usage in test/o45 - fixed.
  10. #47 - crashing on Windows - unable to reproduce with go 1.3.1 on windows 8. Appears to be fixed by changes for #68.
  11. #83 - see example in test/o83 - fixed.
  12. #82 - see example in test/o82 - fixed.
  13. #52 - see example in test/o52 - fixed.
  14. #67 - see example in test/o67 - fixed.
  15. Identified the problem where a emit is sent from client to server and server seems to discard/ignore the emit. This is caused by an invalid paramter and an ignored error message. Code review for all discarded/ignored error messages in progress.

FAQ

  1. Why is this not a fork of the original? A: I can't figure out how to make a fork and change the name of the package on github.com. Since a variety of outside tools hurl over the "-" and ".io" in the directory name I just made a copy and started at the beginning. My apologies to anybody that feels offended by this approach.

Documentation

Overview

go-socket.io is the implement of socket.io in Go (golang).

It is compatible with node.js implementation.

Index

Constants

View Source
const Protocol = 4

Variables

View Source
var (
	DbLogMessage  = false
	LogMessage, _ = strconv.ParseBool(os.Getenv("SOCKETIO_LOG_MESSAGE"))
)

Functions

This section is empty.

Types

type Attachment

type Attachment struct {

	// Data is the ReadWriter of the attachment data.
	Data io.ReadWriter
	// contains filtered or unexported fields
}

Attachment is an attachment handler used in emit args. All attachments will send as binary in transport layer. When use attachment, make sure use as pointer.

For example:

type Arg struct {
    Title string `json:"title"`
    File *Attachment `json:"file"`
}

f, _ := os.Open("./some_file")
arg := Arg{
    Title: "some_file",
    File: &Attachment{
        Data: f,
    }
}

socket.Emit("send file", arg)
socket.On("get file", func(so Socket, arg Arg) {
    b, _ := ioutil.ReadAll(arg.File.Data)
})

func (Attachment) MarshalJSON

func (a Attachment) MarshalJSON() ([]byte, error)

func (*Attachment) UnmarshalJSON

func (a *Attachment) UnmarshalJSON(b []byte) error

type BroadcastAdaptor

type BroadcastAdaptor interface {

	// Join lets socket join the t room.
	Join(room string, socket Socket) error

	// Leave let socket leave the room.
	Leave(room string, socket Socket) error

	// Send will send the message with args to room. If ignore is not nil, it won't send to the socket ignore.
	Send(ignore Socket, room, message string, args ...interface{}) error
}

BroadcastAdaptor is the adaptor to handle broadcast.

type EventHandlerFunc

type EventHandlerFunc func(so *Socket, message string, args [][]byte) error

PJS - could have it return more than just an error, if "rmsg" and "rbody" - then emit response? that makes it more like a RPC - call a func get back a response

type Namespace

type Namespace interface {

	// Name returns the name of namespace.
	Name() string

	// Of returns the namespace with given name.
	Of(name string) Namespace

	// On registers the function f to handle message.
	On(message string, f interface{}) error
}

Namespace is the name space of socket.io handler.

type Server

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

Server is the server of socket.io.

func NewServer

func NewServer(transportNames []string) (*Server, error)

NewServer returns the server supported given transports. If transports is nil, server will use ["polling", "websocket"] as default.

func (*Server) BroadcastTo

func (s *Server) BroadcastTo(room, message string, args ...interface{})

Server level broadcasts function.

func (Server) Name

func (n Server) Name() string

func (Server) Of

func (n Server) Of(name string) Namespace

func (*Server) ServeHTTP

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

ServeHTTP handles http request.

func (*Server) SetAdaptor

func (s *Server) SetAdaptor(adaptor BroadcastAdaptor)

SetAdaptor sets the adaptor of broadcast. Default is in-process broadcast implement.

func (*Server) SetAllowRequest

func (s *Server) SetAllowRequest(f func(*http.Request) error)

SetAllowRequest sets the middleware function when establish connection. If it return non-nil, connection won't be established. Default will allow all request.

func (*Server) SetAllowUpgrades

func (s *Server) SetAllowUpgrades(allow bool)

SetAllowUpgrades sets whether server allows transport upgrade. Default is true.

func (*Server) SetCookie

func (s *Server) SetCookie(prefix string)

SetCookie sets the name of cookie which used by engine.io. Default is "io".

func (*Server) SetMaxConnection

func (s *Server) SetMaxConnection(n int)

SetMaxConnection sets the max connetion. Default is 1000.

func (*Server) SetNewId

func (s *Server) SetNewId(f func(*http.Request) string)

SetNewId sets the callback func to generate new connection id. By default, id is generated from remote addr + current time stamp

func (*Server) SetPingInterval

func (s *Server) SetPingInterval(t time.Duration)

SetPingInterval sets the interval of ping. Default is 25s.

func (*Server) SetPingTimeout

func (s *Server) SetPingTimeout(t time.Duration)

SetPingTimeout sets the timeout of ping. When time out, server will close connection. Default is 60s.

func (*Server) SetSessionManager

func (s *Server) SetSessionManager(sessions engineio.Sessions)

SetSessionsManager sets the sessions as server's session manager. Default sessions is single process manager. You can custom it as load balance.

type Socket

type Socket interface {
	Id() string                                                  // Id returns the session id of socket.
	Rooms() []string                                             // Rooms returns the rooms name joined now.
	Request() *http.Request                                      // Request returns the first http request when established connection.
	On(message string, f interface{}) error                      // On registers the function f to handle message.
	OnAny(f interface{}) error                                   // Register a function that will get called on any message
	Emit(message string, args ...interface{}) error              // Emit emits the message with given args.
	Join(room string) error                                      // Join joins the room.
	Leave(room string) error                                     // Leave leaves the room.
	BroadcastTo(room, message string, args ...interface{}) error // BroadcastTo broadcasts the message to the room with given args.
}

Socket is the socket object of socket.io.

Directories

Path Synopsis
examples
test
o45
o52
o67
o82
o83

Jump to

Keyboard shortcuts

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