websocket

package module
v1.10.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2023 License: Apache-2.0 Imports: 17 Imported by: 0

README

websocket GoDoc License

This is a websocket implementation supporting Go1.7+, which is inspired by websockify and websocket.

Difference from gorilla/websocket
  • gorilla/websocket only has a goroutine to read from websocket and a goroutine to write to websocket, that's, read or write can be done concurrently.
  • Though this library cannot read from websocket concurrently, it's able to write to websocket concurrently. Moreover, it will be enhanced to read concurrently.

Install

$ go get -u github.com/xgfone/go-websocket

VNC Proxy on WebSocket

The sub-package vncproxy provides a HTTP handler about VNC Proxy on Websocket.

Example

Websocket Server Example
package main

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

	"github.com/xgfone/go-websocket"
)

var upgrader = websocket.Upgrader{
	MaxMsgSize:  1024,
	Timeout:     time.Second * 30,
	CheckOrigin: func(r *http.Request) bool { return true },
}

func websocketHandler(rw http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(rw, r, nil)
	if err != nil {
		log.Printf("failed to upgrade to websocket: %s\n", err)
		return
	}

	ws.Run(func(msgType int, message []byte) {
		switch msgType {
		case websocket.MsgTypeBinary:
			ws.SendBinaryMsg(message)
		case websocket.MsgTypeText:
			ws.SendTextMsg(message)
		}
	})
}

func main() {
	http.ListenAndServe(":80", http.HandlerFunc(websocketHandler))
}
Websocket Client Example
package main

import (
	"fmt"
	"time"

	"github.com/xgfone/go-websocket"
)

func main() {
	ws, err := websocket.NewClientWebsocket("ws://127.0.0.1/")
	if err == nil {
		go func() {
			tick := time.NewTicker(time.Second * 10)
			defer tick.Stop()
			for {
				select {
				case now := <-tick.C:
					if err := ws.SendTextMsg([]byte(now.String())); err != nil {
						fmt.Println(err)
						return
					}
				}
			}
		}()

		err = ws.Run(func(msgType int, msg []byte) {
			fmt.Printf("Receive: %s\n", string(msg))
		})
	}
	fmt.Println(err)
}

The client will output like this:

Receive: 2019-07-13 18:33:47.951688 +0800 CST m=+10.007139340
Receive: 2019-07-13 18:33:57.951479 +0800 CST m=+20.006605995
Receive: 2019-07-13 18:34:07.948628 +0800 CST m=+30.003442484
Receive: 2019-07-13 18:34:17.949763 +0800 CST m=+40.004270178
Receive: 2019-07-13 18:34:27.947877 +0800 CST m=+50.002081112
Receive: 2019-07-13 18:34:37.949986 +0800 CST m=+60.003888082
...

Documentation

Overview

Package websocket is websocket library implemented by Go, which is inspired by websockify in noVNC.

Index

Constants

View Source
const (
	MsgTypeContinue = 0x0
	MsgTypeText     = 0x1
	MsgTypeBinary   = 0x2
	MsgTypeClose    = 0x8
	MsgTypePing     = 0x9
	MsgTypePong     = 0xa
)

Predefine message types, that's, opcode defined in RFC6455 section 5.2.

View Source
const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"

GUID is a UUID defined in RFC6455 1.2.

Variables

View Source
var (
	CloseNormalClosure           = 1000
	CloseGoingAway               = 1001
	CloseProtocolError           = 1002
	CloseUnsupportedData         = 1003
	CloseNoStatusReceived        = 1005
	CloseAbnormalClosure         = 1006
	CloseInvalidFramePayloadData = 1007
	ClosePolicyViolation         = 1008
	CloseMessageTooBig           = 1009
	CloseMandatoryExtension      = 1010
	CloseInternalServerErr       = 1011
	CloseTLSHandshake            = 1015
)

Predefine closure status code

Functions

This section is empty.

Types

type ClientOption added in v1.10.0

type ClientOption struct {
	// MaxLine represents the number of the characters of the longest line
	// which is 1024 by default.
	MaxLine int

	// Origin is used to set the Origin header.
	Origin string

	// Protocal is used to set the Sec-Websocket-Protocol header.
	Protocol []string

	// Header is the additional header to do websocket handshake.
	Header http.Header

	// Config is used by the default DialTLS to open a TCP/TLS connection.
	Config *tls.Config

	// Dial is used to open a TCP connection to addr, which is by default
	//   net.Dial("tcp", addr)
	Dial func(addr string) (net.Conn, error)

	// DialTLS is used to open a TCP/TLS connection to addr, which is by default
	//   tls.Dial("tcp", addr, ClientOption.Config)
	DialTLS func(addr string) (net.Conn, error)

	// GenerateHandshakeChallenge is used to generate a challenge
	// for websocket handshake.
	//
	// If missing, it will use the default implementation.
	GenerateHandshakeChallenge func() []byte
}

ClientOption is used to configure the client websocket.

Notice: all the options are optional.

type Message added in v1.0.0

type Message struct {
	// The type of the message, MsgTypeText or MsgTypeBinary
	Type int

	// The message body.
	//
	// For the fragmented message, it contains the datas of all the fragmented.
	Data []byte
}

Message represents a websocket message.

type Upgrader

type Upgrader struct {
	BufferSize   int // The default is 2048KB.
	MaxMsgSize   int // The default is no limit.
	Subprotocols []string
	Timeout      time.Duration // The default is no timeout.

	CheckOrigin  func(*http.Request) bool
	Authenticate func(*http.Request) bool
}

Upgrader is used to upgrade HTTP connection to websocket.

func (Upgrader) Upgrade

func (u Upgrader) Upgrade(w http.ResponseWriter, r *http.Request,
	responseHeader http.Header) (*Websocket, error)

Upgrade upgrades the HTTP connection to websocket.

type Websocket

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

Websocket implements a websocket interface.

Notice:

  1. It does not support the extension.
  2. The sending functions SendXxx can be called concurrently with the unfragmented messages, but the receiving functions, RecvMsg or Run, cannot be done like that.

func NewClientWebsocket added in v1.10.0

func NewClientWebsocket(wsurl string, option ...ClientOption) (ws *Websocket, err error)

NewClientWebsocket returns a new client websocket to connect to wsurl.

func NewWebsocket

func NewWebsocket(conn net.Conn) *Websocket

NewWebsocket creates an websocket.

Notice: the websocket handshake must have finished.

func (*Websocket) IsClosed added in v1.0.0

func (ws *Websocket) IsClosed() bool

IsClosed reports whether the underlying connection has been closed.

func (*Websocket) LocalAddr

func (ws *Websocket) LocalAddr() net.Addr

LocalAddr returns the local network address.

func (*Websocket) RecvMsg

func (ws *Websocket) RecvMsg() (messages []Message, err error)

RecvMsg receives and returns the websocket message.

Notice:

  1. If it returns an error, the underlying connection has been closed.
  2. It only returns the text or binary message, not the control message. So the message type be only MsgTypeText or MsgTypeBinary.
  3. The message data must not be cached, such as putting it into channel.

func (*Websocket) RemoteAddr

func (ws *Websocket) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

func (*Websocket) Run added in v1.0.0

func (ws *Websocket) Run(handle func(msgType int, message []byte)) error

Run runs forever until the connection is closed and returned the error.

When receiving a websocket message, it will handle it by calling handle().

Notice:

  1. msgType be only MsgTypeText or MsgTypeBinary.
  2. The message data must not be cached, such as putting it into channel.

func (*Websocket) SendBinaryMsg

func (ws *Websocket) SendBinaryMsg(message []byte, fin ...bool) error

SendBinaryMsg sends a binary message.

If fin is false, the message will be fragmented.

Notice: when sending fragmented message, you should not send another message until this fragmented message is sent totally.

func (*Websocket) SendClose added in v1.0.0

func (ws *Websocket) SendClose(code int, reason string) error

SendClose termiates the websocket connection gracefully, which will send a close frame to the peer then close the underlying connection.

func (*Websocket) SendPing added in v1.0.0

func (ws *Websocket) SendPing(data []byte) error

SendPing sends a ping control message.

func (*Websocket) SendPong added in v1.0.0

func (ws *Websocket) SendPong(data []byte) error

SendPong sends a pong control message.

func (*Websocket) SendTextMsg

func (ws *Websocket) SendTextMsg(message []byte, fin ...bool) error

SendTextMsg sends a text message.

If fin is false, the message will be fragmented.

Notice: when sending fragmented message, you should not send another message until this fragmented message is sent totally.

func (*Websocket) SetBufferSize added in v1.0.0

func (ws *Websocket) SetBufferSize(size int) *Websocket

SetBufferSize sets the buffer size of websocket.

The default is 2048.

func (*Websocket) SetClient added in v1.0.0

func (ws *Websocket) SetClient() *Websocket

SetClient sets the websocket is a client.

func (*Websocket) SetCloseNotice added in v1.10.0

func (ws *Websocket) SetCloseNotice(cb func()) *Websocket

SetCloseNotice sets the notice function that the connection is closed, that's, the callback cb will be called when the connection is closed.

func (*Websocket) SetDeadline

func (ws *Websocket) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines associated with the connection. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

A deadline is an absolute time after which I/O operations fail with a timeout (see type Error) instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to Read or Write. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.

An idle timeout can be implemented by repeatedly extending the deadline after successful Read or Write calls.

A zero value for t means I/O operations will not time out.

func (*Websocket) SetDeadlineByDuration added in v1.0.0

func (ws *Websocket) SetDeadlineByDuration(d time.Duration) error

SetDeadlineByDuration is equal to SetDeadline(time.Now().Add(d)) if d > 0.

func (*Websocket) SetMaxMsgSize added in v1.0.0

func (ws *Websocket) SetMaxMsgSize(size int) *Websocket

SetMaxMsgSize sets the max message size of websocket.

The default(0) is no limit.

func (*Websocket) SetPingHander

func (ws *Websocket) SetPingHander(h func(ws *Websocket, data []byte)) *Websocket

SetPingHander sets the ping handler.

func (*Websocket) SetPongHander

func (ws *Websocket) SetPongHander(h func(ws *Websocket, data []byte)) *Websocket

SetPongHander sets the pong handler.

func (*Websocket) SetProtocol added in v1.0.0

func (ws *Websocket) SetProtocol(protocol string) *Websocket

SetProtocol sets the selected protocol of websocket.

func (*Websocket) SetReadDeadline

func (ws *Websocket) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out.

func (*Websocket) SetReadDeadlineByDuration added in v1.0.0

func (ws *Websocket) SetReadDeadlineByDuration(d time.Duration) error

SetReadDeadlineByDuration is equal to SetReadDeadline(time.Now().Add(d)) if d > 0.

func (*Websocket) SetTimeout added in v1.0.0

func (ws *Websocket) SetTimeout(timeout time.Duration) *Websocket

SetTimeout sets the timeout to receive and send the websocket message.

func (*Websocket) SetWriteDeadline

func (ws *Websocket) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future Write calls and any currently-blocked Write call. Even if write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out.

func (*Websocket) SetWriteDeadlineByDuration added in v1.0.0

func (ws *Websocket) SetWriteDeadlineByDuration(d time.Duration) error

SetWriteDeadlineByDuration is equal to SetWriteDeadline(time.Now().Add(d)) if d > 0.

func (*Websocket) Subprotocol added in v1.0.0

func (ws *Websocket) Subprotocol() string

Subprotocol returns the selected protocol.

Directories

Path Synopsis
Package vncproxy provides a HTTP handler about VNC Proxy on Websocket.
Package vncproxy provides a HTTP handler about VNC Proxy on Websocket.

Jump to

Keyboard shortcuts

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