basicws

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2024 License: MIT Imports: 8 Imported by: 2

README

go-basic-websocket

Simple WebSocket client

Example program using https://www.websocket.org/echo.html:

package main

import (
	"fmt"
	"github.com/dnsge/go-basic-websocket"
	"net/http"
	"sync"
	"time"
)

func main() {
	// simple echo websocket
	headers := http.Header{
		"User-Agent": []string{"echo-client/1.0"},
	}
	ws := basicws.NewBasicWebsocket("wss://echo.websocket.org", headers)
	wg := sync.WaitGroup{}

	ws.OnConnect = func() {
		fmt.Println("Connected to server!")

		time.AfterFunc(time.Second*3, func() {
			ws.SendString("Hello, world!")
		})
	}

	ws.OnMessage = func(b []byte) error {
		fmt.Printf("Received message: %s\n", string(b))
		ws.Disconnect()
		wg.Done()
		return nil
	}

	wg.Add(1)
	_ = ws.Connect()

	wg.Wait()
}

Output:

Connected to server!
Received message: Hello, world!

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	AlreadyConnectedError = errors.New("already connected")
)

Functions

This section is empty.

Types

type BasicWebsocket

type BasicWebsocket struct {

	// Time in between being disconnected and reconnecting
	ReconnectTime time.Duration
	// Whether the websocket should try to reconnect after getting disconnected
	AutoReconnect bool
	// Callback function to be called on websocket connect/reconnect
	OnConnect func()
	// Callback function to be called on every message received
	OnMessage func(b []byte) error
	// Callback function to be called on errors
	OnError func(err error)
	// contains filtered or unexported fields
}

func NewBasicWebsocket

func NewBasicWebsocket(url string, header http.Header) *BasicWebsocket

Create a new BasicWebsocket with a URL and Header

func (*BasicWebsocket) Connect

func (ws *BasicWebsocket) Connect() error

Connect to the server

func (*BasicWebsocket) Disconnect

func (ws *BasicWebsocket) Disconnect() bool

Disconnect and, if specified, reconnect afterwards. Returns whether reconnecting

func (*BasicWebsocket) ForceDisconnect

func (ws *BasicWebsocket) ForceDisconnect()

Disconnect without reconnecting

func (*BasicWebsocket) IsConnected

func (ws *BasicWebsocket) IsConnected() bool

func (*BasicWebsocket) Reconnect

func (ws *BasicWebsocket) Reconnect() error

Immediately disconnect and reconnect

func (*BasicWebsocket) SendBytes

func (ws *BasicWebsocket) SendBytes(bytes []byte)

Send bytes to server (blocking)

func (*BasicWebsocket) SendJSON

func (ws *BasicWebsocket) SendJSON(data interface{}) error

Marshal an interface into JSON, then send bytes to server (blocking)

func (*BasicWebsocket) SendString

func (ws *BasicWebsocket) SendString(s string)

Send string to server (blocking)

Jump to

Keyboard shortcuts

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