gowebsocket

package module
v0.0.0-...-7608f89 Latest Latest
Warning

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

Go to latest
Published: May 10, 2021 License: Apache-2.0 Imports: 12 Imported by: 0

README

GoWebsocket

Gorilla websocket based simplified client implementation in GO.

Overview

This client provides following easy to implement functionality

  • Support for emitting and receiving text and binary data
  • Data compression
  • Concurrency control
  • Proxy support
  • Setting request headers
  • Subprotocols support
  • SSL verification enable/disable

To install use

    go get github.com/sacOO7/gowebsocket

Description

Create instance of Websocket by passing url of websocket-server end-point

    //Create a client instance
    socket := gowebsocket.New("ws://echo.websocket.org/")
    

Important Note : url to websocket server must be specified with either ws or wss.

Connecting to server
  • For connecting to server:
    //This will send websocket handshake request to socketcluster-server
    socket.Connect()
  • For connecting wit a cancellable context:
    //This will send websocket handshake request to socketcluster-server
    ctx, cancel := context.WithCancel()
    socket.ConnectWithContext()
Registering All Listeners
    package main
    
    import (
    	"log"
    	"github.com/sacOO7/gowebsocket"
        "os"
        "os/signal"
    )
    
    func main() {
    
        interrupt := make(chan os.Signal, 1)
        signal.Notify(interrupt, os.Interrupt)
        
    	socket := gowebsocket.New("ws://echo.websocket.org/");
    	
    	socket.OnConnected = func(socket gowebsocket.Socket) {
    		log.Println("Connected to server");
    	};
    	
        socket.OnConnectError = func(err error, socket gowebsocket.Socket) {
            log.Println("Recieved connect error ", err)
        };
        
    	socket.OnTextMessage = func(message string, socket gowebsocket.Socket) {
    		log.Println("Recieved message " + message)
    	};
    	
    	socket.OnBinaryMessage = func(data [] byte, socket gowebsocket.Socket) {
            log.Println("Recieved binary data ", data)
        };
        
    	socket.OnPingReceived = func(data string, socket gowebsocket.Socket) {
    		log.Println("Recieved ping " + data)
    	};
    	
    	socket.OnPongReceived = func(data string, socket gowebsocket.Socket) {
            log.Println("Recieved pong " + data)
        };
        
    	socket.OnDisconnected = func(err error, socket gowebsocket.Socket) {
    		log.Println("Disconnected from server ")
    		return
    	};
    	
    	socket.Connect()
    	
        for {
            select {
            case <-interrupt:
                log.Println("interrupt")
                socket.Close()
                return
            }
        }
    }
    
Sending Text message
    socket.SendText("Hi there, this is my sample test message")
Sending Binary data
    token := make([]byte, 4)
    // rand.Read(token) putting some random value in token
    socket.SendBinary(token)
Closing the connection with server
    socket.Close()
Setting request headers
	socket.RequestHeader.Set("Accept-Encoding","gzip, deflate, sdch")
	socket.RequestHeader.Set("Accept-Language","en-US,en;q=0.8")
	socket.RequestHeader.Set("Pragma","no-cache")
	socket.RequestHeader.Set("User-Agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36")
	
Setting proxy server
  • It can be set using connectionOptions by providing url to proxy server
    socket.ConnectionOptions = gowebsocket.ConnectionOptions {
       Proxy: gowebsocket.BuildProxy("http://example.com"),
    }
Setting data compression, ssl verification and subprotocols
  • It can be set using connectionOptions inside socket
    socket.ConnectionOptions = gowebsocket.ConnectionOptions {
        UseSSL:true,
        UseCompression:true,
        Subprotocols: [] string{"chat","superchat"},
    }
  • ConnectionOptions needs to be applied before connecting to server
  • Please checkout examples/gowebsocket directory for detailed code..

License

Apache License, Version 2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildProxy

func BuildProxy(rawURL string) func(*http.Request) (*url.URL, error)

BuildProxy creates an http proxy

Types

type ConnectionOptions

type ConnectionOptions struct {
	UseCompression bool
	UseSSL         bool
	Proxy          func(*http.Request) (*url.URL, error)
	Subprotocols   []string
}

ConnectionOptions contains connection options

type ReconnectionOptions

type ReconnectionOptions struct {
}

ReconnectionOptions provides options for reconnecting to the websocket TODO Yet to be done

type Socket

type Socket struct {
	Conn              *websocket.Conn
	WebsocketDialer   *websocket.Dialer
	URL               string
	ConnectionOptions ConnectionOptions
	RequestHeader     http.Header
	OnConnected       func(socket Socket)
	OnTextMessage     func(message string, socket Socket)
	OnBinaryMessage   func(data []byte, socket Socket)
	OnConnectError    func(err error, socket Socket)
	OnDisconnected    func(err error, socket Socket)
	OnPingReceived    func(data string, socket Socket)
	OnPongReceived    func(data string, socket Socket)
	IsConnected       bool
	Timeout           time.Duration
	// contains filtered or unexported fields
}

Socket provides a websocket request

func New

func New(url string) Socket

New creates a new websocket for the given url

func (*Socket) Close

func (socket *Socket) Close()

Close closese the websocket

func (*Socket) Connect

func (socket *Socket) Connect()

Connect connects to the websocket server

func (*Socket) ConnectWithContext

func (socket *Socket) ConnectWithContext(ctx context.Context)

ConnectWithContext connects to the websocket server using a context object to allow the user to cancel the requests

func (Socket) EnableLogging

func (socket Socket) EnableLogging()

EnableLogging enables the logger

func (Socket) GetLogger

func (socket Socket) GetLogger() logging.Logger

GetLogger gets the logger object

func (*Socket) SendBinary

func (socket *Socket) SendBinary(data []byte)

SendBinary sends a binary message to the websocket

func (*Socket) SendText

func (socket *Socket) SendText(message string)

SendText sends a test message to the server

Directories

Path Synopsis
examples
gowebsocket command

Jump to

Keyboard shortcuts

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