ws

package
v1.8.2 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2024 License: MIT Imports: 7 Imported by: 0

README

WebSocket

ws is based on the github.com/gorilla/websocket library.


Example of use

1. default setting

Server side code example:

package main

import (
	"context"
	"log"
    "github.com/zhufuyi/sponge/pkg/ws"
    "github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	
	r.GET("/ws", func(c *gin.Context) {
		s := ws.NewServer(c.Writer, c.Request, loopReceiveMessage) // default setting
		err := s.Run(context.Background())
		if err != nil {
			log.Println("webSocket server error:", err)
		}
	})
	
    err := r.Run(":8080")
    if err != nil {
        panic(err)
    }
}

func loopReceiveMessage(ctx context.Context, conn *ws.Conn) {
    for {
        messageType, message, err := conn.ReadMessage()
        // handle message
		log.Println(messageType, message, err)
    }
}

Client side code example:

package main

import (
	"strconv"
	"log"
	"time"
	"github.com/zhufuyi/sponge/pkg/ws"
	"github.com/gorilla/websocket"
)

var wsURL = "ws://localhost:8080/ws"

func main() {
	c, err := ws.NewClient(wsURL)
	if err != nil {
		log.Println("connect error:", err)
		return
	}
	defer c.Close()

	go func() {
		for {
			_, message, err := c.GetConn().ReadMessage()
			if err != nil {
				log.Println("client read error:", err)
				return
			}
			log.Printf("client received: %s", message)
		}
	}()
	
	for i := 0; i < 5; i++ {
		data := "Hello, World " + strconv.Itoa(i)
		err = c.GetConn().WriteMessage(websocket.TextMessage, []byte(data))
		if err != nil {
			log.Println("write error:", err)
		}
		time.Sleep(100 * time.Millisecond)
	}
}

2. custom setting

Server side custom setting, options such as ws.Upgrader ws.WithMaxMessageWaitPeriod can be set.

package main

import (
	"context"
	"log"
	"time"
	"http"
    "github.com/zhufuyi/sponge/pkg/ws"
    "github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

func main() {
	r := gin.Default()
	ug := &websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}	
	r.GET("/ws", func(c *gin.Context) {
		s := ws.NewServer(c.Writer, c.Request, loopReceiveMessage,
			ws.WithUpgrader(ug),
			ws.WithMaxMessageWaitPeriod(time.Minute),
		)
		err := s.Run(context.Background())
		if err != nil {
			log.Println("webSocket server error:", err)
		}
	})
	
    err := r.Run(":8080")
    if err != nil {
        panic(err)
    }
}

func loopReceiveMessage(ctx context.Context, conn *ws.Conn) {
	for {
		messageType, message, err := conn.ReadMessage()
		// handle message
		log.Println(messageType, message, err)
	}
}

Client side custom setting, options such as ws.Dialer ws.WithPingInterval can be set.

package main

import (
	"strconv"
	"log"
	"time"
	"github.com/zhufuyi/sponge/pkg/ws"
	"github.com/gorilla/websocket"
)

var wsURL = "ws://localhost:8080/ws"

func main() {
	c, err := NewClient(wsURL,
		WithDialer(websocket.DefaultDialer),
		WithPing(time.Second*10),
	)
	if err != nil {
		log.Println("connect error:", err)
		return
	}
	defer c.Close()

	go func() {
		for {
			_, message, err := c.GetConn().ReadMessage()
			if err != nil {
				log.Println("client read error:", err)
				return
			}
			log.Printf("client received: %s", message)
		}
	}()

	for i := 5; i < 10; i++ {
		data := "Hello, World " + strconv.Itoa(i)
		err = c.GetConn().WriteMessage(websocket.TextMessage, []byte(data))
		if err != nil {
			log.Println("write error:", err)
		}
		time.Sleep(100 * time.Millisecond)
	}

	<-time.After(time.Minute)
}

Documentation

Overview

Package ws provides a WebSocket server implementation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsClientClose

func IsClientClose(err error) bool

IsClientClose returns true if the error is caused by client close.

func IsServerClose

func IsServerClose(err error) bool

IsServerClose returns true if the error is caused by server close.

Types

type Client

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

Client is a wrapper of gorilla/websocket.

func NewClient

func NewClient(url string, opts ...ClientOption) (*Client, error)

NewClient creates a new client.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection. Note: if set pingDialInterval, the Close method must be called, otherwise it will cause the goroutine to leak

func (*Client) GetConn

func (c *Client) GetConn() *websocket.Conn

func (*Client) Reconnect

func (c *Client) Reconnect() error

Reconnect the websocket server.

type ClientOption

type ClientOption func(*clientOptions)

ClientOption is a functional option for the client.

func WithDialer

func WithDialer(dialer *websocket.Dialer) ClientOption

WithDialer sets the dialer for the client.

func WithPing

func WithPing(interval time.Duration) ClientOption

WithPing sets the interval for sending ping message to the server.

func WithRequestHeader

func WithRequestHeader(header http.Header) ClientOption

WithRequestHeader sets the request header for the client.

type Conn

type Conn = websocket.Conn

Conn is a WebSocket connection.

type LoopFn

type LoopFn func(ctx context.Context, conn *Conn)

LoopFn is the function that is called for each WebSocket connection.

type Server

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

Server is a WebSocket server.

func NewServer

func NewServer(w http.ResponseWriter, r *http.Request, loopFn LoopFn, opts ...ServerOption) *Server

NewServer creates a new WebSocket server.

func (*Server) Run

func (s *Server) Run(ctx context.Context) error

Run runs the WebSocket server.

type ServerOption

type ServerOption func(*serverOptions)

ServerOption is a functional option for the Server.

func WithMaxMessageWaitPeriod

func WithMaxMessageWaitPeriod(period time.Duration) ServerOption

WithMaxMessageWaitPeriod sets the maximum waiting period for a message before closing the connection.

func WithResponseHeader

func WithResponseHeader(header http.Header) ServerOption

WithResponseHeader sets the response header for the WebSocket upgrade response.

func WithUpgrader

func WithUpgrader(upgrader *websocket.Upgrader) ServerOption

WithUpgrader sets the WebSocket upgrader for the server.

Jump to

Keyboard shortcuts

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