A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://pkg.go.dev/github.com/coder/websocket@v1.8.13 below:

websocket package - github.com/coder/websocket - Go Packages

Package websocket implements the RFC 6455 WebSocket protocol.

https://tools.ietf.org/html/rfc6455

Use Dial to dial a WebSocket server.

Use Accept to accept a WebSocket client.

Conn represents the resulting WebSocket connection.

The examples are the best way to understand how to correctly use the library.

The wsjson subpackage contain helpers for JSON and protobuf messages.

More documentation at https://github.com/coder/websocket.

Wasm ΒΆ

The client side supports compiling to Wasm. It wraps the WebSocket browser API.

See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket

Some important caveats to be aware of:

package main

import (
	"log"
	"net/http"

	"github.com/coder/websocket"
)

func main() {
	// This handler demonstrates how to safely accept cross origin WebSockets
	// from the origin example.com.
	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
			OriginPatterns: []string{"example.com"},
		})
		if err != nil {
			log.Println(err)
			return
		}
		c.Close(websocket.StatusNormalClosure, "cross origin WebSocket accepted")
	})

	err := http.ListenAndServe("localhost:8080", fn)
	log.Fatal(err)
}

This example demonstrates a echo server.

package main

import ()

func main() {
	// https://github.com/nhooyr/websocket/tree/master/internal/examples/echo
}

This example demonstrates full stack chat with an automated test.

package main

import ()

func main() {
	// https://github.com/nhooyr/websocket/tree/master/internal/examples/chat
}
package main

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

	"github.com/coder/websocket"
	"github.com/coder/websocket/wsjson"
)

func main() {
	// This handler demonstrates how to correctly handle a write only WebSocket connection.
	// i.e you only expect to write messages and do not expect to read any messages.
	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			log.Println(err)
			return
		}
		defer c.CloseNow()

		ctx, cancel := context.WithTimeout(r.Context(), time.Minute*10)
		defer cancel()

		ctx = c.CloseRead(ctx)

		t := time.NewTicker(time.Second * 30)
		defer t.Stop()

		for {
			select {
			case <-ctx.Done():
				c.Close(websocket.StatusNormalClosure, "")
				return
			case <-t.C:
				err = wsjson.Write(ctx, c, "hi")
				if err != nil {
					log.Println(err)
					return
				}
			}
		}
	})

	err := http.ListenAndServe("localhost:8080", fn)
	log.Fatal(err)
}

This section is empty.

This section is empty.

NetConn converts a *websocket.Conn into a net.Conn.

It's for tunneling arbitrary protocols over WebSockets. Few users of the library will need this but it's tricky to implement correctly and so provided in the library. See https://github.com/nhooyr/websocket/issues/100.

Every Write to the net.Conn will correspond to a message write of the given type on *websocket.Conn.

The passed ctx bounds the lifetime of the net.Conn. If cancelled, all reads and writes on the net.Conn will be cancelled.

If a message is read that is not of the correct type, the connection will be closed with StatusUnsupportedData and an error will be returned.

Close will close the *websocket.Conn with StatusNormalClosure.

When a deadline is hit and there is an active read or write goroutine, the connection will be closed. This is different from most net.Conn implementations where only the reading/writing goroutines are interrupted but the connection is kept alive.

The Addr methods will return the real addresses for connections obtained from websocket.Accept. But for connections obtained from websocket.Dial, a mock net.Addr will be returned that gives "websocket" for Network() and "websocket/unknown-addr" for String(). This is because websocket.Dial only exposes a io.ReadWriteCloser instead of the full net.Conn to us.

When running as WASM, the Addr methods will always return the mock address described above.

A received StatusNormalClosure or StatusGoingAway close frame will be translated to io.EOF when reading.

Furthermore, the ReadLimit is set to -1 to disable it.

AcceptOptions represents Accept's options.

CloseError is returned when the connection is closed with a status and reason.

Use Go 1.13's errors.As to check for this error. Also see the CloseStatus helper.

CompressionMode represents the modes available to the permessage-deflate extension. See https://tools.ietf.org/html/rfc7692

Works in all modern browsers except Safari which does not implement the permessage-deflate extension.

Compression is only used if the peer supports the mode selected.

const (
	
	
	
	CompressionDisabled CompressionMode = iota

	
	
	
	
	
	
	
	
	
	
	
	CompressionContextTakeover

	
	
	
	
	
	
	
	
	
	
	
	CompressionNoContextTakeover
)

Conn represents a WebSocket connection. All methods may be called concurrently except for Reader and Read.

You must always read from the connection. Otherwise control frames will not be handled. See Reader and CloseRead.

Be sure to call Close on the connection when you are finished with it to release associated resources.

On any error from any method, the connection is closed with an appropriate reason.

This applies to context expirations as well unfortunately. See https://github.com/nhooyr/websocket/issues/242#issuecomment-633182220

Accept accepts a WebSocket handshake from a client and upgrades the the connection to a WebSocket.

Accept will not allow cross origin requests by default. See the InsecureSkipVerify and OriginPatterns options to allow cross origin requests.

Accept will write a response to w on all errors.

Note that using the http.Request Context after Accept returns may lead to unexpected behavior (see http.Hijacker).

package main

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

	"github.com/coder/websocket"
	"github.com/coder/websocket/wsjson"
)

func main() {
	// This handler accepts a WebSocket connection, reads a single JSON
	// message from the client and then closes the connection.

	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			log.Println(err)
			return
		}
		defer c.CloseNow()

		ctx, cancel := context.WithTimeout(r.Context(), time.Second*10)
		defer cancel()

		var v interface{}
		err = wsjson.Read(ctx, c, &v)
		if err != nil {
			log.Println(err)
			return
		}

		c.Close(websocket.StatusNormalClosure, "")
	})

	err := http.ListenAndServe("localhost:8080", fn)
	log.Fatal(err)
}

Dial performs a WebSocket handshake on url.

The response is the WebSocket handshake response from the server. You never need to close resp.Body yourself.

If an error occurs, the returned response may be non nil. However, you can only read the first 1024 bytes of the body.

This function requires at least Go 1.12 as it uses a new feature in net/http to perform WebSocket handshakes. See docs on the HTTPClient option and https://github.com/golang/go/issues/26937#issuecomment-415855861

URLs with http/https schemes will work and are interpreted as ws/wss.

package main

import (
	"context"
	"log"
	"time"

	"github.com/coder/websocket"
	"github.com/coder/websocket/wsjson"
)

func main() {
	// Dials a server, writes a single JSON message and then
	// closes the connection.

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.CloseNow()

	err = wsjson.Write(ctx, c, "hi")
	if err != nil {
		log.Fatal(err)
	}

	c.Close(websocket.StatusNormalClosure, "")
}

Close performs the WebSocket close handshake with the given status code and reason.

It will write a WebSocket close frame with a timeout of 5s and then wait 5s for the peer to send a close frame. All data messages received from the peer during the close handshake will be discarded.

The connection can only be closed once. Additional calls to Close are no-ops.

The maximum length of reason must be 125 bytes. Avoid sending a dynamic reason.

Close will unblock all goroutines interacting with the connection once complete.

CloseNow closes the WebSocket connection without attempting a close handshake. Use when you do not want the overhead of the close handshake.

CloseRead starts a goroutine to read from the connection until it is closed or a data message is received.

Once CloseRead is called you cannot read any messages from the connection. The returned context will be cancelled when the connection is closed.

If a data message is received, the connection will be closed with StatusPolicyViolation.

Call CloseRead when you do not expect to read any more messages. Since it actively reads from the connection, it will ensure that ping, pong and close frames are responded to. This means c.Ping and c.Close will still work as expected.

This function is idempotent.

Ping sends a ping to the peer and waits for a pong. Use this to measure latency or ensure the peer is responsive. Ping must be called concurrently with Reader as it does not read from the connection but instead waits for a Reader call to read the pong.

TCP Keepalives should suffice for most use cases.

package main

import (
	"context"
	"log"
	"time"

	"github.com/coder/websocket"
)

func main() {
	// Dials a server and pings it 5 times.

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.CloseNow()

	// Required to read the Pongs from the server.
	ctx = c.CloseRead(ctx)

	for i := 0; i < 5; i++ {
		err = c.Ping(ctx)
		if err != nil {
			log.Fatal(err)
		}
	}

	c.Close(websocket.StatusNormalClosure, "")
}

Read is a convenience method around Reader to read a single message from the connection.

Reader reads from the connection until there is a WebSocket data message to be read. It will handle ping, pong and close frames as appropriate.

It returns the type of the message and an io.Reader to read it. The passed context will also bound the reader. Ensure you read to EOF otherwise the connection will hang.

Call CloseRead if you do not expect any data messages from the peer.

Only one Reader may be open at a time.

If you need a separate timeout on the Reader call and the Read itself, use time.AfterFunc to cancel the context passed in. See https://github.com/nhooyr/websocket/issues/87#issue-451703332 Most users should not need this.

SetReadLimit sets the max number of bytes to read for a single message. It applies to the Reader and Read methods.

By default, the connection has a message read limit of 32768 bytes.

When the limit is hit, the connection will be closed with StatusMessageTooBig.

Set to -1 to disable.

Subprotocol returns the negotiated subprotocol. An empty string means the default protocol.

Write writes a message to the connection.

See the Writer method if you want to stream a message.

If compression is disabled or the compression threshold is not met, then it will write the message in a single frame.

Writer returns a writer bounded by the context that will write a WebSocket message of type dataType to the connection.

You must close the writer once you have written the entire message.

Only one writer can be open at a time, multiple calls will block until the previous writer is closed.

DialOptions represents Dial's options.

StatusCode represents a WebSocket status code. https://tools.ietf.org/html/rfc6455#section-7.4

CloseStatus is a convenience wrapper around Go 1.13's errors.As to grab the status code from a CloseError.

-1 will be returned if the passed error is nil or not a CloseError.

package main

import (
	"context"
	"log"
	"time"

	"github.com/coder/websocket"
)

func main() {
	// Dials a server and then expects to be disconnected with status code
	// websocket.StatusNormalClosure.

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil)
	if err != nil {
		log.Fatal(err)
	}
	defer c.CloseNow()

	_, _, err = c.Reader(ctx)
	if websocket.CloseStatus(err) != websocket.StatusNormalClosure {
		log.Fatalf("expected to be disconnected with StatusNormalClosure but got: %v", err)
	}
}

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4