WebSocket

WebSocket allows to maintain a two-way connection between the browser and gox-server.

Through this connection, the server and the client can issue typical events, exchange values, make requests with response and manage groups or channels in real time.

GOX provides an API to define server behavior by websocket/index.gox and a JavaScript module to use the connection from the browser.


Workflow

Integration begins by creating the file websocket/index.gox.

text
my-project/
└── websocket/
    └── index.gox

The function Index receives the socket associated with each connection and records its events.

gox
module websocket

import "github.com/gox-lang/gox"

func Index(socket *gox.Socket) gox.WebSocket {
    socket.When("connect", func(isReconnect bool) {
        socket.Emit("welcome", "Hola, George")
    })

    socket.On("message", func(message string) {
        socket.Emit("message", message)
    })
}

From the browser, the WebSocket client is imported by @gox/websocket.

javascript
import { Socket } from "@gox/websocket"

const socket = new Socket()

socket.when("connect", isReconnect => {
    console.log("Conexión establecida", { isReconnect })
})

socket.on("welcome", message => {
    console.log(message)
})

socket.on("message", message => {
    console.log(message)
})

socket.emit("message", "Hola desde el cliente")

new Socket() automatically starts the connection. Once established, events issued from any of the ends are sent to the handlers registered on the other.


Server

The file websocket/index.gox defines the main entry point of WebSocket.

gox
func Index(socket *gox.Socket) gox.WebSocket

Each connection receives its own instance of gox.Socket.

From there it is possible:

  • Check the identity of the connection.
  • Access the associated session.
  • Consult the request that originated the handshake.
  • Record life cycle events.
  • Register application events.
  • To issue events to the client.
  • Manage groups.
  • Check out other sockets from the same session.
  • Disconnect the connection.

Each socket retains access to the session used during the handshake. Sessions to know your life cycle and the values that can be stored in it.

The WebSocket service can be activated and set up its waiting times, message limits, Heartbeat, queues, buffers and compression from app/websocket.gox.

See WebSocket Settings to know the available options.

To coordinate WebSocket communication, sessions, groups and channels between various bodies of gox-server, set up a cluster by redisadapter.

See Cluster configuration to know how to activate the communication distributed among the instances.

See Socket to know how to create websocket/index.gox and use the server API.


Client

The module @gox/websocket provides the API used from JavaScript or TypeScript.

javascript
import { Socket } from "@gox/websocket"

const socket = new Socket()

The client manages the connection, reconnection and event transport. It also allows you to create channels and make requests that expect a server response.

It can be used from the built-in components by the system of Client.

See Client to know their creation, configuration and connection states.


Lifecycle

Events recorded by means of When on the server and when in the client allow to respond to changes in the connection.

The main socket provides events for:

EventDescription
handshakeDecides whether the request can establish the connection.
connectIt runs when the connection is ready.
disconnectIt runs when the connection ends.
errorIt receives the errors produced during its operation.

GOX also manages the client's reconnection and allows to distinguish an initial connection from a reconnection.

See Lifecycle to know these events and the behavior of the connection.


Events

Events recorded by means of On on the server and on in the client receive the values issued from the opposite end.

gox
socket.On("greeting", func(name string) {
    log.Printf("Hola, %s", name)
})
javascript
socket.emit("greeting", "George")

The parameters declared by the handler establish the event contract. GOX validates the amount and types of the values received before running the function.

See Events to learn to register and issue events in both directions.


Requests

An emission can also expect a response from the opposite end.

gox
var theme string

if err := socket.Emit("getTheme").Await(&theme); err != nil {
    log.Printf("No se pudo obtener el tema: %v", err)
}

This mechanism retains the event model, but links each request to a single response.

See Requests to know how to declare handlers with a response and wait for their results.


Values

WebSocket events can carry simple values, structures, collections, forms, HTML and files.

GOX retains the compatible types during communication and uses binary transfers when the value requires it.

See Values to know the types admitted and their representation on the server and the client.


Groups

The groups allow to temporarily gather several sockets under the same name.

gox
if err := socket.Join("administrators"); err != nil {
    log.Printf("No se pudo unir el socket al grupo: %v", err)
}

A socket can belong to several groups and receive events aimed only at its members.

See Groups to know how to join, go out and issue events to groups.


Channels

The channels provide independent communication spaces on the same WebSocket connection.

Each channel can define its own validation, life cycle and event set.

text
websocket/
├── index.gox
└── chat/
    └── index.gox

The channels can be shared or identified by a key, which can represent conversations, resources or dynamic spaces.

See Channels to know how to declare and use them from the client.


Errors

The errors of connection, transport, validation and execution are delivered by the error events of the socket or the corresponding channel.

Each error provides information about your code, phase, related event and possibility of retrying.

See Errors to know the types of error and how to process them.


Documentation

DocumentContent
SocketInput point and socket API on the server.
ClientSocket creation and management in the browser.
LifecycleHandshake, connection, reconnection and disconnection.
EventsRegistration and issue of events.
RequestsEvents waiting for an response.
ValuesTypes and values that can be transferred.
GroupsTemporary grouping of sockets.
ChannelsIndependent spaces within a connection.
ErrorsSocket and channel errors.

Best practices

  • It uses events with clear names and related to the operation they represent.
  • Declares specific parameters so that GOX can validate the values received.
  • Keep the handlers brief and delegate business logic to specialized functions or packages.
  • It uses requests only when the issuer needs a response.
  • It uses groups to temporarily collect sockets and channels to model independent communication spaces.
  • Process the errors through the corresponding event.
  • No store references to the context received during the handshake.
  • Do not send through WebSocket information that the client is not authorized to consult.

See also

Next step

Continue with Socket to learn how to create websocket/index.gox and configure the behavior of each connection on the server.

Socket