Websockets
WebSocket is a protocol that enables two-way persistent communication channels over TCP connections. It is used for applications such as chat, stock tickers, games, anywhere you want real-time functionality in a web application.
Use WebSockets when you need to work directly with a socket connection. For example, you might need the best possible performance for a real-time game.
First of all, read the kataras/neffos wiki to master the new websocket library built for net/http and Iris.
It comes pre-installed with Iris, however you can install it separately by executing the following shell command.
1
$ go get github.com/kataras/[email protected]
Copied!
Continue by reading how you can register the neffos websocket server into your Iris application.
A list of comprehensive examples working with websockets can be found at: https://github.com/kataras/iris/tree/master/_examples/websocket.
The iris/websocket subpackage contains (only) Iris-specific migrations and helpers for the neffos websocket framework one.
For example, to gain access of the request's Context you can call the websocket.GetContext(Conn) from inside an event message handler/callback:
1
// GetContext returns the Iris Context from a websocket connection.
2
func GetContext(c *neffos.Conn) Context
Copied!
To register a websocket neffos.Server to a route use the websocket.Handler function:
1
// IDGenerator is an iris-specific IDGenerator for new connections.
2
type IDGenerator func(Context) string
3
4
// Handler returns an Iris handler to be served in a route of an Iris application.
5
// Accepts the neffos websocket server as its first input argument
6
// and optionally an Iris-specific `IDGenerator` as its second one.
7
func Handler(s *neffos.Server, IDGenerator ...IDGenerator) Handler
Copied!
Usage
1
import (
2
"github.com/kataras/neffos"
3
"github.com/kataras/iris/v12/websocket"
4
)
5
6
// [...]
7
8
onChat := func(ns *neffos.NSConn, msg neffos.Message) error {
9
ctx := websocket.GetContext(ns.Conn)
10
// [...]
11
return nil
12
}
13
14
app := iris.New()
15
ws := neffos.New(websocket.DefaultGorillaUpgrader, neffos.Namespaces{
16
"default": neffos.Events {
17
"chat": onChat,
18
},
19
})
20
app.Get("/websocket_endpoint", websocket.Handler(ws))
Copied!
Last modified 1yr ago
Export as PDF
Copy link