peer

package module
v0.0.0-...-5b28944 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2024 License: Apache-2.0 Imports: 19 Imported by: 3

README

Golang PeerJS

A Golang port of PeerJS

Implementation

  • Datachannel
  • Mediachannel
  • Test coverage > 80%
  • Signalling server
  • Interoperability tests

Docs

Go Reference

⚠️ Note: While the Javascript PeerJS documentation often applies to this library, there are differences, namely:

  • All methods and properties are in PascalCase.
  • Enum values are represented as seperate constants.
  • All peer event callback functions should take a generic interface{} parameter, and then cast the interface{} to the appropriate peerjs-go type.
  • Blocked peer event callback functions will block other peerjs-go events from firing.
  • Refer to the go package docs whenever unsure.
Unsupported features
  • Payload de/encoding based on js-binarypack is not supported.
  • Message chunking (should be already done in recent browser versions)

Usage example

See _examples folder


package main

import (
	"log"
	"time"

	peer "github.com/muka/peerjs-go"
)

func main() {
	peer1, _ := peer.NewPeer("peer1", peer.NewOptions())
	defer peer1.Close()

	peer2, _ := peer.NewPeer("peer2", peer.NewOptions())
	defer peer2.Close()

	peer2.On("connection", func(data interface{}) {
		conn2 := data.(*peer.DataConnection)
		conn2.On("data", func(data interface{}) {
			// Will print 'hi!'
			log.Printf("Received: %#v: %s\n", data, data)
		})
	})

	conn1, _ := peer1.Connect("peer2", nil)
	conn1.On("open", func(data interface{}) {
		for {
			conn1.Send([]byte("hi!"), false)
			<-time.After(time.Millisecond * 1000)
		}
	})

	select {}
}

Peer server

This library includes a GO based peer server in the /server folder

Documentation:

Go Reference

Example usage
package main

import (
	"log"

	peerjsServer "github.com/muka/peerjs-go/server"
)

func main() {
	serverOptions := peerjsServer.NewOptions()
	// These are the default values NewOptions() creates:
	serverOptions.Port = 9000
	serverOptions.Host = "0.0.0.0"
	serverOptions.LogLevel = "info"
	serverOptions.ExpireTimeout = 5000
	serverOptions.AliveTimeout = 60000
	serverOptions.Key = "peerjs"
	serverOptions.Path = "/"
	serverOptions.ConcurrentLimit = 5000
	serverOptions.AllowDiscovery = false
	serverOptions.CleanupOutMsgs = 1000

	server := peerjsServer.New(serverOptions)
	defer server.Stop()

	if err := server.Start(); err != nil {
		log.Printf("Error starting peerjs server: %s", err)
	}

	select{}
}
Docker

A docker image for the GO based peer server is available at opny/peer-server built for Raspberry Pi and PCs

Standalone

To build a standalone GO based Peerjs server executable, run go build ./cmd/server/main.go in the repository folder. To set the server options, create a peer.yaml configuration file in the same folder as the executable with the following options:

Available Server Options:

  • Host String
  • Port Int
  • LogLevel String
  • ExpireTimeout Int64
  • AliveTimeout Int64
  • Key String
  • Path String
  • ConcurrentLimit Int
  • AllowDiscovery Bool
  • CleanupOutMsgs Int

Documentation

Index

Constants

View Source
const (
	//DataChannelIDPrefix used as prefix for random ID
	DataChannelIDPrefix = "dc_"
	//MaxBufferedAmount max amount to buffer
	MaxBufferedAmount = 8 * 1024 * 1024
)
View Source
const DefaultBrowser = "peerjs-go"

DefaultBrowser is the browser name

View Source
const MediaChannelIDPrefix = "mc_"

MediaChannelIDPrefix the media channel connection id prefix

Variables

View Source
var DefaultKey = "peerjs"

DefaultKey is the default API key

Functions

This section is empty.

Types

type API

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

API wrap calls to API server

func NewAPI

func NewAPI(opts Options) API

NewAPI initiate a new API client

func (*API) ListAllPeers

func (a *API) ListAllPeers() ([]byte, error)

ListAllPeers return the list of available peers

func (*API) RetrieveID

func (a *API) RetrieveID() ([]byte, error)

RetrieveID retrieve a ID

type AnswerOption

type AnswerOption struct {
	// SDPTransform transformation function for SDP message
	SDPTransform func(string) string
}

AnswerOption wraps answer options

type BaseConnection

type BaseConnection struct {
	emitter.Emitter

	//Provider is the peer instance
	Provider *Peer
	// DataChannel A reference to the RTCDataChannel object associated with the connection.
	DataChannel *webrtc.DataChannel
	// The optional label passed in or assigned by PeerJS when the connection was initiated.
	Label string
	// Metadata Any type of metadata associated with the connection, passed in by whoever initiated the connection.
	Metadata interface{}
	// Open This is true if the connection is open and ready for read/write.
	Open bool
	// PeerConnection A reference to the RTCPeerConnection object associated with the connection.
	PeerConnection *webrtc.PeerConnection
	// Reliable Whether the underlying data channels are reliable; defined when the connection was initiated.
	Reliable bool
	// Serialization The serialization format of the data sent over the connection. Can be binary (default), binary-utf8, json, or none.
	Serialization string
	// Type defines the type for connections
	Type string
	// BufferSize The number of messages queued to be sent once the browser buffer is no longer full.
	BufferSize int
	// contains filtered or unexported fields
}

BaseConnection shared base connection

func (*BaseConnection) Close

func (c *BaseConnection) Close() error

Close closes the data connection

func (*BaseConnection) GetID

func (c *BaseConnection) GetID() string

GetID return the connection ID

func (*BaseConnection) GetMetadata

func (c *BaseConnection) GetMetadata() interface{}

GetMetadata return the connection metadata

func (*BaseConnection) GetOptions

func (c *BaseConnection) GetOptions() ConnectionOptions

GetOptions return the connection configuration

func (*BaseConnection) GetPeerConnection

func (c *BaseConnection) GetPeerConnection() *webrtc.PeerConnection

GetPeerConnection return the underlying WebRTC PeerConnection

func (*BaseConnection) GetPeerID

func (c *BaseConnection) GetPeerID() string

GetPeerID return the connection peer ID

func (*BaseConnection) GetProvider

func (c *BaseConnection) GetProvider() *Peer

GetProvider return the peer provider

func (*BaseConnection) GetType

func (c *BaseConnection) GetType() string

GetType return the connection type

func (*BaseConnection) HandleMessage

func (c *BaseConnection) HandleMessage(msg *models.Message) error

HandleMessage handles incoming messages

func (*BaseConnection) SetPeerConnection

func (c *BaseConnection) SetPeerConnection(pc *webrtc.PeerConnection)

SetPeerConnection set the underlying WebRTC PeerConnection

type Connection

type Connection interface {
	GetType() string
	GetID() string
	GetPeerID() string
	GetProvider() *Peer
	GetMetadata() interface{}
	GetPeerConnection() *webrtc.PeerConnection
	SetPeerConnection(pc *webrtc.PeerConnection)
	Close() error
	HandleMessage(*models.Message) error
	Emit(string, interface{})
	GetOptions() ConnectionOptions
}

Connection shared interface

type ConnectionOptions

type ConnectionOptions struct {
	//ConnectionID
	ConnectionID string
	//Payload
	Payload models.Payload
	//Label A unique label by which you want to identify this data connection. If left unspecified, a label will be generated at random.
	Label string
	// Metadata associated with the connection, passed in by whoever initiated the connection.
	Metadata interface{}
	// Serialization. "raw" is the default. PeerJS supports other options, like encodings for JSON objects, but those aren't supported by this library.
	Serialization string
	// Reliable whether the underlying data channels should be reliable (e.g. for large file transfers) or not (e.g. for gaming or streaming). Defaults to false.
	Reliable bool
	// Stream contains the reference to a media stream
	Stream *MediaStream
	// Originator indicate if the originator
	Originator bool
	// SDP contains SDP information
	SDP webrtc.SessionDescription
	// Debug level for debug taken. See Options
	Debug int8
	// SDPTransform transformation function for SDP message
	SDPTransform func(string) string
	// MediaEngine override the default pion webrtc MediaEngine used in negotiating media channels. This allows you to specify your own supported media formats and parameters.
	MediaEngine *webrtc.MediaEngine
}

ConnectionOptions wrap optios for Peer Connect()

func NewConnectionOptions

func NewConnectionOptions() *ConnectionOptions

NewConnectionOptions return a ConnectionOptions with defaults

type DataConnection

type DataConnection struct {
	BaseConnection
	// contains filtered or unexported fields
}

DataConnection track a connection with a remote Peer

func NewDataConnection

func NewDataConnection(peerID string, peer *Peer, opts ConnectionOptions) (*DataConnection, error)

NewDataConnection create new DataConnection

func (*DataConnection) Close

func (d *DataConnection) Close() error

Close allows user to close connection

func (*DataConnection) HandleMessage

func (d *DataConnection) HandleMessage(message *models.Message) error

HandleMessage handles incoming messages

func (*DataConnection) Initialize

func (d *DataConnection) Initialize(dc *webrtc.DataChannel)

Initialize called by the Negotiator when the DataChannel is ready

func (*DataConnection) Send

func (d *DataConnection) Send(data []byte, chunked bool) error

Send allows user to send data.

type MediaConnection

type MediaConnection struct {
	BaseConnection
	Open bool
	// contains filtered or unexported fields
}

MediaConnection track a connection with a remote Peer

func NewMediaConnection

func NewMediaConnection(id string, peer *Peer, opts ConnectionOptions) (*MediaConnection, error)

NewMediaConnection create new MediaConnection

func (*MediaConnection) AddStream

func (m *MediaConnection) AddStream(tr *webrtc.TrackRemote)

AddStream adds a stream to the MediaConnection

func (*MediaConnection) Answer

func (m *MediaConnection) Answer(tl webrtc.TrackLocal, options *AnswerOption)

Answer open the media connection with the remote peer

func (*MediaConnection) Close

func (m *MediaConnection) Close() error

Close allows user to close connection

func (*MediaConnection) GetLocalStream

func (m *MediaConnection) GetLocalStream() *MediaStream

GetLocalStream returns the local stream

func (*MediaConnection) GetRemoteStream

func (m *MediaConnection) GetRemoteStream() *MediaStream

GetRemoteStream returns the remote stream

func (*MediaConnection) HandleMessage

func (m *MediaConnection) HandleMessage(message *models.Message) error

type MediaStream

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

MediaStream A stream of media content. A stream consists of several tracks such as video or audio tracks. Each track is specified as an instance of MediaStreamTrack.

func NewMediaStreamWithTrack

func NewMediaStreamWithTrack(tracks []MediaStreamTrack) *MediaStream

NewMediaStreamWithTrack create a mediastream with tracks

func (*MediaStream) AddTrack

func (m *MediaStream) AddTrack(t MediaStreamTrack)

AddTrack add a track

func (*MediaStream) GetTracks

func (m *MediaStream) GetTracks() []MediaStreamTrack

GetTracks returns a list of tracks

func (*MediaStream) RemoveTrack

func (m *MediaStream) RemoveTrack(t MediaStreamTrack)

RemoveTrack remove a track

type MediaStreamTrack

type MediaStreamTrack interface {
	// ID is the unique identifier for this Track. This should be unique for the
	// stream, but doesn't have to globally unique. A common example would be 'audio' or 'video'
	// and StreamID would be 'desktop' or 'webcam'
	ID() string

	// StreamID is the group this track belongs too. This must be unique
	StreamID() string

	// Kind controls if this TrackLocal is audio or video
	Kind() webrtc.RTPCodecType
}

MediaStreamTrack interaface that wraps together TrackLocal and TrackRemote

type Negotiator

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

Negotiator manages all negotiations between Peers

func NewNegotiator

func NewNegotiator(conn Connection, opts ConnectionOptions) *Negotiator

NewNegotiator initiate a new negotiator

func (*Negotiator) Cleanup

func (n *Negotiator) Cleanup()

Cleanup clean up the negotiatior internal state

func (*Negotiator) HandleCandidate

func (n *Negotiator) HandleCandidate(iceInit *webrtc.ICECandidateInit) error

HandleCandidate handles a candidate

func (*Negotiator) StartConnection

func (n *Negotiator) StartConnection(opts ConnectionOptions) error

StartConnection Returns a PeerConnection object set up correctly (for data, media). */

type Options

type Options struct {
	// Key API key for the cloud PeerServer. This is not used for servers other than 0.peerjs.com.
	Key string
	// Server host. Defaults to 0.peerjs.com. Also accepts '/' to signify relative hostname.
	Host string
	//Port Server port. Defaults to 443.
	Port int
	//PingInterval Ping interval in ms. Defaults to 5000.
	PingInterval int
	//Path The path where your self-hosted PeerServer is running. Defaults to '/'.
	Path string
	//Secure true if you're using SSL.
	Secure bool
	//Configuration hash passed to RTCPeerConnection. This hash contains any custom ICE/TURN server configuration. Defaults to { 'iceServers': [{ 'urls': 'stun:stun.l.google.com:19302' }], 'sdpSemantics': 'unified-plan' }
	Configuration webrtc.Configuration
	// Debug
	// Prints log messages depending on the debug level passed in. Defaults to 0.
	// 0 Prints no logs.
	// 1 Prints only errors.
	// 2 Prints errors and warnings.
	// 3 Prints all logs.
	Debug int8
	//Token a string to group peers
	Token string
}

Options store Peer options

func NewOptions

func NewOptions() Options

NewOptions return Peer options with defaults

type Peer

type Peer struct {
	emitter.Emitter
	ID string
	// contains filtered or unexported fields
}

Peer expose the PeerJS API

func NewPeer

func NewPeer(id string, opts Options) (*Peer, error)

NewPeer initializes a new Peer object

func (*Peer) AddConnection

func (p *Peer) AddConnection(peerID string, connection Connection)

AddConnection add the connection to the peer

func (*Peer) Call

func (p *Peer) Call(peerID string, track webrtc.TrackLocal, opts *ConnectionOptions) (*MediaConnection, error)

Call returns a MediaConnection to the specified peer. See documentation for a complete list of options. To add more than one track to the call, set the stream parameter in the ConnectionOptions.

  • Example: connectionOpts := *peer.NewConnectionOptions() connectionOpts.Stream = peer.NewMediaStreamWithTrack([]peer.MediaStreamTrack{track1, track2}) Peer.Call("peer-id", nil, &connectionOpts)

func (*Peer) Close

func (p *Peer) Close()

Close closes the peer instance

func (*Peer) Connect

func (p *Peer) Connect(peerID string, opts *ConnectionOptions) (*DataConnection, error)

Connect returns a DataConnection to the specified peer. See documentation for a complete list of options.

func (*Peer) Destroy

func (p *Peer) Destroy()

destroys the Peer: closes all active connections as well as the connection to the server. Warning: The peer can no longer create or accept connections after being destroyed.

func (*Peer) Disconnect

func (p *Peer) Disconnect()

Disconnect disconnects the Peer's connection to the PeerServer. Does not close any active connections. Warning: The peer can no longer create or accept connections after being disconnected. It also cannot reconnect to the server.

func (*Peer) EmitError

func (p *Peer) EmitError(errType string, err error)

EmitError emits an error

func (*Peer) GetConnection

func (p *Peer) GetConnection(peerID string, connectionID string) (Connection, bool)

GetConnection return a connection based on peerID and connectionID

func (*Peer) GetDestroyed

func (p *Peer) GetDestroyed() bool

GetDestroyed return this peer's is destroyed state true if this peer and all of its connections can no longer be used.

func (*Peer) GetDisconnected

func (p *Peer) GetDisconnected() bool

GetDisconnected return this peer's is disconnected state returns false if there is an active connection to the PeerServer.

func (*Peer) GetMessages

func (p *Peer) GetMessages(connectionID string) []models.Message

GetMessages Retrieve messages from lost message store

func (*Peer) GetOpen

func (p *Peer) GetOpen() bool

GetSocket return this peer's is open state

func (*Peer) GetOptions

func (p *Peer) GetOptions() Options

GetOptions return options

func (*Peer) GetSocket

func (p *Peer) GetSocket() *Socket

GetSocket return this peer's socket connection

func (*Peer) ListAllPeers

func (p *Peer) ListAllPeers() ([]string, error)

ListAllPeers Get a list of available peer IDs. If you're running your own server, you'll want to set allow_discovery: true in the PeerServer options. If you're using the cloud server, email team@peerjs.com to get the functionality enabled for your key.

func (*Peer) Reconnect

func (p *Peer) Reconnect() error

Reconnect Attempts to reconnect with the same ID

func (*Peer) RemoveConnection

func (p *Peer) RemoveConnection(connection Connection)

RemoveConnection removes the connection from the peer

type PeerError

type PeerError struct {
	Err  error
	Type string
}

func (PeerError) Error

func (e PeerError) Error() string

func (PeerError) Unwrap

func (e PeerError) Unwrap() error

type Socket

type Socket struct {
	emitter.Emitter
	// contains filtered or unexported fields
}

Socket abstract websocket exposing an event emitter like interface

func NewSocket

func NewSocket(opts Options) *Socket

NewSocket create a socket instance

func (*Socket) Close

func (s *Socket) Close() error

Close close the websocket connection

func (*Socket) Send

func (s *Socket) Send(msg []byte) error

Send send a message

func (*Socket) Start

func (s *Socket) Start(id string, token string) error

Start initiate the connection

type SocketEvent

type SocketEvent struct {
	Type    string
	Message *models.Message
	Error   error
}

SocketEvent carries an event from the socket

Directories

Path Synopsis
_examples
cmd

Jump to

Keyboard shortcuts

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