websocket

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2018 License: MIT Imports: 17 Imported by: 0

README

websocket (WebSocket client and server for Go)

About

This is an easy-to-use WebSocket client and server implementation in Go. It passes the Autobahn Test Suite.

Usage

Full documentation here.

Installing
Go 1.10

vgo get -u github.com/gbrlsnchs/websocket

Go 1.11

go get -u github.com/gbrlsnchs/websocket

Importing
import (
	// ...

	"github.com/gbrlsnchs/websocket"
)

Examples

Upgrading an HTTP request and listening to messages
func upgradingHandler(w http.ResponseWriter, r *http.Request) {
	ws, err := websocket.UpgradeHTTP(w, r)
	if err != nil {
		// handle error
	}

	for ws.Next() {
		ws.SetWriteOpcode(ws.Opcode())
		ws.Write(ws.Payload())
	}
	if err := ws.Err(); err != nil {
		fmt.Println(err)
	}
	fmt.Println(ws.CloseCode())
}
Openning connection to a WebSocket server (client mode)
ws, err := websocket.Open("ws://echo.websocket.org")
if err != nil {
	// handle error
}

ws.Write([]byte("Hello, WebSocket!"))

for ws.Next() {
	fmt.Printf("Message sent from server: %s\n", ws.Payload())
}
if err := ws.Err(); err != nil {
	fmt.Println(err)
	os.Exit(1)
}
fmt.Println(ws.CloseCode())

Contributing

How to help

Documentation

Index

Constants

View Source
const (
	OpcodeText   = 0x1
	OpcodeBinary = 0x2
)

Variables

This section is empty.

Functions

This section is empty.

Types

type WebSocket

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

WebSocket is a websocket instance that may be either a client or a server depending on how it is created.

func Open

func Open(address string) (*WebSocket, error)

Open creates a WebSocket instance in client mode. The address must use either "ws" or "wss" protocols. If the port is omitted, it assumes port 80 for "ws" and port 443 for "wss".

func UpgradeHTTP

func UpgradeHTTP(w http.ResponseWriter, r *http.Request) (*WebSocket, error)

UpgradeHTTP switches the protocol from HTTP to the WebSocket Protocol.

func (*WebSocket) Close

func (ws *WebSocket) Close() error

Close closes the connection manually by sending the close code 1000.

func (*WebSocket) CloseCode

func (ws *WebSocket) CloseCode() uint16

func (*WebSocket) Err

func (ws *WebSocket) Err() error

func (*WebSocket) Next

func (ws *WebSocket) Next() bool

func (*WebSocket) Opcode

func (ws *WebSocket) Opcode() uint8

func (*WebSocket) Payload

func (ws *WebSocket) Payload() []byte

func (*WebSocket) Read

func (ws *WebSocket) Read(b []byte) (int, error)

func (*WebSocket) SetCloseCode

func (ws *WebSocket) SetCloseCode(cc uint16) error

func (*WebSocket) SetWriteOpcode

func (ws *WebSocket) SetWriteOpcode(opcode uint8)

func (WebSocket) Write

func (w WebSocket) Write(b []byte) (int, error)

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

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