ws

package module
v1.2.7 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2021 License: MIT Imports: 16 Imported by: 0

README

ws

Simple to use golang websocket client/server library + vanilla js client library.

Example

    package main

import (
	"log"
	"net/http"
	"time"

	"github.com/night-codes/ws"
	// "github.com/night-codes/ws/fasthttp/connector"
	// "github.com/night-codes/ws/tokay/connector"
	// "github.com/night-codes/ws/gin/connector"
	"github.com/night-codes/ws/http/connector"
)

func main() {
	go server()
	time.Sleep(time.Second)
	go client()
	time.Sleep(time.Second * 5)
}

// === SERVER ===
func server() {
	handler, mainWS := connector.New()

	// Listen command from the client and send answer
	mainWS.Read("test", func(a *ws.Adapter) {
		data := a.Data()
		log.Println("1)", string(data))
		a.Send("pong")
	})

	// Listen command from the client without answer
	mainWS.Read("command", func(a *ws.Adapter) {
		data := a.Data()
		log.Println("3)", string(data))
	})

	// Send command to each client and wait for answer
	go func() {
		time.Sleep(time.Second * 2)
		for _, conn := range mainWS.GetConnects() {
			if result, err := conn.Request("client test", "client ping", time.Second); err == nil {
				log.Println("5)", string(result))
			}
		}
	}()

	// Listen and serve:

	// net/http:
	http.Handle("/myws", handler) // [net/http]
	log.Fatal(http.ListenAndServe(":8080", nil))

	// fasthttp:
	/* fasthttp.ListenAndServe(":8080", func(ctx *fasthttp.RequestCtx) {
		switch string(ctx.Path()) {
		case "/myws":
			handler(ctx)
		default:
			ctx.Error("Unsupported path", fasthttp.StatusNotFound)
		}
	}) */

	// tokay
	/* app := tokay.New()
	app.GET("/myws", handler)
	panic(app.Run(":8080", "Application started at %s")) */

	// gin
	/* app := gin.New()
	app.GET("/myws", handler)
	panic(app.Run(":8080")) */
}

// === CLIENT ===
func client() {
	conn := ws.NewClient("ws://localhost:8080/myws")

	// Send command to the server and wait for answer
	if result, err := conn.Request("test", "ping", time.Second); err == nil {
		log.Println("2)", string(result))
	}

	// Send command to the server without answer waiting
	conn.Send("command", "Server command 1")
	conn.Send("command", "Server command 2")
	conn.Send("command", "Server command 3")

	// Listen command from the server
	conn.Read("client test", func(a *ws.Adapter) {
		data := a.Data()
		log.Println("4)", string(data))
		a.Send("client pong")
	})
}

MIT License

Copyright (c) 2018 Oleksiy Chechel

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Adapter

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

Adapter is slice of Connect instances

func (*Adapter) Close

func (a *Adapter) Close()

Close all connects

func (*Adapter) Command

func (a *Adapter) Command() string

Command returns request command

func (*Adapter) Connection

func (a *Adapter) Connection() *Connection

Connection returns adapter connect instance

func (*Adapter) Context

func (a *Adapter) Context() NetContext

Context returns copy of NetContext

func (*Adapter) Data

func (a *Adapter) Data() []byte

Data returns client message

func (*Adapter) JSONData

func (a *Adapter) JSONData(obj interface{}) error

JSONData makes json.Unmarshal for client message

func (*Adapter) RequestID

func (a *Adapter) RequestID() int64

RequestID returns adapter.requestID

func (*Adapter) Send

func (a *Adapter) Send(message interface{}) error

Send message to open connection

func (*Adapter) StringData

func (a *Adapter) StringData() string

StringData return string client message without json ""

func (*Adapter) Subscribers

func (a *Adapter) Subscribers(commands string) Connections

Subscribers of commands ("command1,command2" etc.)

func (*Adapter) User

func (a *Adapter) User() *User

User returns connection user

type Channel

type Channel struct {
	UseBinary bool
	// contains filtered or unexported fields
}

Channel is websocket route

func NewChannel added in v1.2.0

func NewChannel() *Channel

NewChannel creates new ws.Channel

func (*Channel) AddConnectFunc

func (channel *Channel) AddConnectFunc(fn func(a *Adapter))

AddConnectFunc add new Connect handler

func (*Channel) AddDisconnectFunc

func (channel *Channel) AddDisconnectFunc(fn func(a *Adapter))

AddDisconnectFunc add new Disconnect handler

func (*Channel) Close

func (channel *Channel) Close()

Close ws instance connections

func (*Channel) Connection

func (channel *Channel) Connection(connID uint64) *Connection

Connection by ID (or empty closed if not found)

func (*Channel) Count

func (channel *Channel) Count() int

Count of connections

func (*Channel) GetConnects

func (channel *Channel) GetConnects() (connectIDs map[uint64]*Connection)

GetConnects from Channel

func (*Channel) GetUsers

func (channel *Channel) GetUsers() (userIDs map[interface{}]*User)

GetUsers from Channel

func (*Channel) Handler added in v1.2.0

func (channel *Channel) Handler(conn ConnIface, context NetContext)

Handler add websocket handler

func (*Channel) Read

func (channel *Channel) Read(command string, fn func(*Adapter))

Read is client message (request) handler

func (*Channel) Send

func (channel *Channel) Send(command string, message interface{}) error

Send message to open connections

func (*Channel) Subscribers

func (channel *Channel) Subscribers(commands string) Connections

Subscribers of commands ("command1,command2" etc.)

func (*Channel) User

func (channel *Channel) User(userID interface{}) *User

User by id

func (*Channel) UsersCount

func (channel *Channel) UsersCount() int

UsersCount is count of users

type Client

type Client struct {
	Reconnect *events.Event
	// contains filtered or unexported fields
}

Client ws instance

func NewClient

func NewClient(url string, debug ...bool) *Client

NewClient makes new WC Client

func (*Client) ChangeURL

func (c *Client) ChangeURL(url string)

ChangeURL for client connection

func (*Client) Close added in v1.2.7

func (c *Client) Close()

Close client connection

func (*Client) Read

func (c *Client) Read(command string, fn func(*Adapter))

Read is client message (request) handler

func (*Client) Request

func (c *Client) Request(command string, message interface{}, timeout ...time.Duration) ([]byte, error)

Request information from server

func (*Client) Send

func (c *Client) Send(command string, message interface{}, requestID ...int64) (err error)

Send message to server

func (*Client) Subscribe

func (c *Client) Subscribe(command string)

Subscribe connection to command

func (*Client) UnSubscribe added in v1.2.7

func (c *Client) UnSubscribe(command string)

UnSubscribe from command

type ConnIface added in v1.2.0

type ConnIface interface {
	SetReadLimit(limit int64)
	ReadMessage() (messageType int, p []byte, err error)
	WriteMessage(messageType int, data []byte) error
	Close() error
}

Channel is websocket route

type Connection

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

Connection instance [Copying Connection by value is forbidden. Use pointer to Connection instead.]

func (*Connection) Close

func (c *Connection) Close()

Close connect

func (*Connection) Context

func (c *Connection) Context() NetContext

Context returns copy of NetContext

func (*Connection) ID

func (c *Connection) ID() uint64

ID of Connection

func (*Connection) IsSubscribed

func (c *Connection) IsSubscribed(commands string) bool

IsSubscribed returns true if Connect subscribed for one of commands ("command1,command2" etc.)

func (*Connection) Origin

func (c *Connection) Origin() string

Origin of connection

func (*Connection) Request

func (c *Connection) Request(command string, message interface{}, timeout ...time.Duration) ([]byte, error)

Request information from client

func (*Connection) Send

func (c *Connection) Send(command string, message interface{}, requestID ...int64) error

Send message to open connect

func (*Connection) Subscribe

func (c *Connection) Subscribe(command string)

Subscribe connection to command

func (*Connection) Subscribers

func (c *Connection) Subscribers(commands string) Connections

Subscribers returns Connects Subscribers of commands ("command1,command2" etc.)

func (*Connection) User

func (c *Connection) User() *User

User returns connection user

type Connections

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

Connections is slice of Connect instances

func (Connections) Add

func (cs Connections) Add(c *Connection)

Add connection to list

func (Connections) Close

func (cs Connections) Close()

Close all connections

func (Connections) Connection

func (cs Connections) Connection(connID uint64) *Connection

Connection by ID (or empty closed if not found)

func (Connections) Send

func (cs Connections) Send(command string, message interface{}) error

Send message to open connect

func (Connections) Subscribers

func (cs Connections) Subscribers(commands string) Connections

Subscribers of commands ("command1,command2" etc.)

type Map

type Map map[string]interface{}

Map is alias for map[string]interface{}

type NetContext

type NetContext interface{}

NetContext is used network context, like *tokay.Context, *gin.Context, echo.Context etc.

type User

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

User instance

func (*User) Close

func (u *User) Close()

Close User's connections

func (*User) Connection

func (u *User) Connection(connID uint64) *Connection

Connection by ID (or empty closed if not found)

func (*User) Count

func (u *User) Count() int

Count of connections

func (*User) GetConnects

func (u *User) GetConnects() (connectIDs map[uint64]*Connection)

GetConnects returns User connections

func (*User) ID

func (u *User) ID() interface{}

ID in users list

func (*User) Send

func (u *User) Send(command string, message interface{}) error

Send message to open user's connections

func (*User) Subscribers

func (u *User) Subscribers(commands string, message interface{}) Connections

Subscribers of commands ("command1,command2" etc.)

Directories

Path Synopsis
fasthttp
gin
http
tokay

Jump to

Keyboard shortcuts

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