mirror of
https://github.com/kataras/iris.git
synced 2025-12-18 02:17:05 +00:00
Another new feature: websocket controller, for real
Former-commit-id: c1a59b86733e890709b52446e22427a17d87f5fc
This commit is contained in:
@@ -105,8 +105,9 @@ var Ws = (function () {
|
||||
t = websocketJSONMessageType;
|
||||
m = JSON.stringify(data);
|
||||
}
|
||||
else {
|
||||
console.log("Invalid, javascript-side should contains an empty second parameter.");
|
||||
else if (data !== null && typeof(data) !== "undefined" ) {
|
||||
// if it has a second parameter but it's not a type we know, then fire this:
|
||||
console.log("unsupported type of input argument passed, try to not include this argument to the 'Emit'");
|
||||
}
|
||||
return this._msg(event, t, m);
|
||||
};
|
||||
|
||||
@@ -106,8 +106,9 @@ class Ws {
|
||||
//propably json-object
|
||||
t = websocketJSONMessageType;
|
||||
m = JSON.stringify(data);
|
||||
} else {
|
||||
console.log("Invalid, javascript-side should contains an empty second parameter.");
|
||||
} else if (data !== null && typeof (data) !== "undefined") {
|
||||
// if it has a second parameter but it's not a type we know, then fire this:
|
||||
console.log("unsupported type of input argument passed, try to not include this argument to the 'Emit'");
|
||||
}
|
||||
|
||||
return this._msg(event, t, m);
|
||||
|
||||
@@ -137,6 +137,9 @@ type (
|
||||
Connection interface {
|
||||
// Emitter implements EmitMessage & Emit
|
||||
Emitter
|
||||
// Err is not nil if the upgrader failed to upgrade http to websocket connection.
|
||||
Err() error
|
||||
|
||||
// ID returns the connection's identifier
|
||||
ID() string
|
||||
|
||||
@@ -181,6 +184,11 @@ type (
|
||||
// Note: the callback(s) called right before the server deletes the connection from the room
|
||||
// so the connection theoretical can still send messages to its room right before it is being disconnected.
|
||||
OnLeave(roomLeaveCb LeaveRoomFunc)
|
||||
// Wait starts the pinger and the messages reader,
|
||||
// it's named as "Wait" because it should be called LAST,
|
||||
// after the "On" events IF server's `Upgrade` is used,
|
||||
// otherise you don't have to call it because the `Handler()` does it automatically.
|
||||
Wait()
|
||||
// Disconnect disconnects the client, close the underline websocket conn and removes it from the conn list
|
||||
// returns the error, if any, from the underline connection
|
||||
Disconnect() error
|
||||
@@ -197,6 +205,7 @@ type (
|
||||
}
|
||||
|
||||
connection struct {
|
||||
err error
|
||||
underline UnderlineConnection
|
||||
id string
|
||||
messageType int
|
||||
@@ -207,6 +216,7 @@ type (
|
||||
onPingListeners []PingFunc
|
||||
onNativeMessageListeners []NativeMessageFunc
|
||||
onEventListeners map[string][]MessageFunc
|
||||
started bool
|
||||
// these were maden for performance only
|
||||
self Emitter // pre-defined emitter than sends message to its self client
|
||||
broadcast Emitter // pre-defined emitter that sends message to all except this
|
||||
@@ -237,6 +247,7 @@ func newConnection(ctx context.Context, s *Server, underlineConn UnderlineConnec
|
||||
onErrorListeners: make([]ErrorFunc, 0),
|
||||
onNativeMessageListeners: make([]NativeMessageFunc, 0),
|
||||
onEventListeners: make(map[string][]MessageFunc, 0),
|
||||
started: false,
|
||||
ctx: ctx,
|
||||
server: s,
|
||||
}
|
||||
@@ -252,6 +263,11 @@ func newConnection(ctx context.Context, s *Server, underlineConn UnderlineConnec
|
||||
return c
|
||||
}
|
||||
|
||||
// Err is not nil if the upgrader failed to upgrade http to websocket connection.
|
||||
func (c *connection) Err() error {
|
||||
return c.err
|
||||
}
|
||||
|
||||
// write writes a raw websocket message with a specific type to the client
|
||||
// used by ping messages and any CloseMessage types.
|
||||
func (c *connection) write(websocketMessageType int, data []byte) error {
|
||||
@@ -322,6 +338,13 @@ func (c *connection) startPinger() {
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *connection) fireOnPing() {
|
||||
// fire the onPingListeners
|
||||
for i := range c.onPingListeners {
|
||||
c.onPingListeners[i]()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *connection) startReader() {
|
||||
conn := c.underline
|
||||
hasReadTimeout := c.server.config.ReadTimeout > 0
|
||||
@@ -503,11 +526,20 @@ func (c *connection) fireOnLeave(roomName string) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *connection) fireOnPing() {
|
||||
// fire the onPingListeners
|
||||
for i := range c.onPingListeners {
|
||||
c.onPingListeners[i]()
|
||||
// Wait starts the pinger and the messages reader,
|
||||
// it's named as "Wait" because it should be called LAST,
|
||||
// after the "On" events IF server's `Upgrade` is used,
|
||||
// otherise you don't have to call it because the `Handler()` does it automatically.
|
||||
func (c *connection) Wait() {
|
||||
if c.started {
|
||||
return
|
||||
}
|
||||
c.started = true
|
||||
// start the ping
|
||||
c.startPinger()
|
||||
|
||||
// start the messages reader
|
||||
c.startReader()
|
||||
}
|
||||
|
||||
func (c *connection) Disconnect() error {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package websocket
|
||||
|
||||
const (
|
||||
// All is the string which the Emitter use to send a message to all
|
||||
// All is the string which the Emitter use to send a message to all.
|
||||
All = ""
|
||||
// Broadcast is the string which the Emitter use to send a message to all except this connection
|
||||
Broadcast = ";ionwebsocket;to;all;except;me;"
|
||||
// Broadcast is the string which the Emitter use to send a message to all except this connection.
|
||||
Broadcast = ";to;all;except;me;"
|
||||
)
|
||||
|
||||
type (
|
||||
|
||||
@@ -109,7 +109,7 @@ type (
|
||||
mu sync.RWMutex // for rooms
|
||||
onConnectionListeners []ConnectionFunc
|
||||
//connectionPool sync.Pool // sadly we can't make this because the websocket connection is live until is closed.
|
||||
handler context.Handler
|
||||
upgrader websocket.Upgrader
|
||||
}
|
||||
)
|
||||
|
||||
@@ -119,10 +119,20 @@ type (
|
||||
//
|
||||
// To serve the built'n javascript client-side library look the `websocket.ClientHandler`.
|
||||
func New(cfg Config) *Server {
|
||||
cfg = cfg.Validate()
|
||||
return &Server{
|
||||
config: cfg.Validate(),
|
||||
config: cfg,
|
||||
rooms: make(map[string][]string, 0),
|
||||
onConnectionListeners: make([]ConnectionFunc, 0),
|
||||
upgrader: websocket.Upgrader{
|
||||
HandshakeTimeout: cfg.HandshakeTimeout,
|
||||
ReadBufferSize: cfg.ReadBufferSize,
|
||||
WriteBufferSize: cfg.WriteBufferSize,
|
||||
Error: cfg.Error,
|
||||
CheckOrigin: cfg.CheckOrigin,
|
||||
Subprotocols: cfg.Subprotocols,
|
||||
EnableCompression: cfg.EnableCompression,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,40 +145,50 @@ func New(cfg Config) *Server {
|
||||
//
|
||||
// To serve the built'n javascript client-side library look the `websocket.ClientHandler`.
|
||||
func (s *Server) Handler() context.Handler {
|
||||
// build the upgrader once
|
||||
c := s.config
|
||||
|
||||
upgrader := websocket.Upgrader{
|
||||
HandshakeTimeout: c.HandshakeTimeout,
|
||||
ReadBufferSize: c.ReadBufferSize,
|
||||
WriteBufferSize: c.WriteBufferSize,
|
||||
Error: c.Error,
|
||||
CheckOrigin: c.CheckOrigin,
|
||||
Subprotocols: c.Subprotocols,
|
||||
EnableCompression: c.EnableCompression,
|
||||
}
|
||||
|
||||
return func(ctx context.Context) {
|
||||
// Upgrade upgrades the HTTP Server connection to the WebSocket protocol.
|
||||
//
|
||||
// The responseHeader is included in the response to the client's upgrade
|
||||
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
|
||||
// application negotiated subprotocol (Sec--Protocol).
|
||||
//
|
||||
// If the upgrade fails, then Upgrade replies to the client with an HTTP error
|
||||
// response.
|
||||
conn, err := upgrader.Upgrade(ctx.ResponseWriter(), ctx.Request(), ctx.ResponseWriter().Header())
|
||||
if err != nil {
|
||||
ctx.Application().Logger().Warnf("websocket error: %v\n", err)
|
||||
ctx.StatusCode(503) // Status Service Unavailable
|
||||
return
|
||||
c := s.Upgrade(ctx)
|
||||
// NOTE TO ME: fire these first BEFORE startReader and startPinger
|
||||
// in order to set the events and any messages to send
|
||||
// the startPinger will send the OK to the client and only
|
||||
// then the client is able to send and receive from Server
|
||||
// when all things are ready and only then. DO NOT change this order.
|
||||
|
||||
// fire the on connection event callbacks, if any
|
||||
for i := range s.onConnectionListeners {
|
||||
s.onConnectionListeners[i](c)
|
||||
}
|
||||
s.handleConnection(ctx, conn)
|
||||
|
||||
// start the ping and the messages reader
|
||||
c.Wait()
|
||||
}
|
||||
}
|
||||
|
||||
// handleConnection creates & starts to listening to a new connection
|
||||
func (s *Server) handleConnection(ctx context.Context, websocketConn UnderlineConnection) {
|
||||
// Upgrade upgrades the HTTP Server connection to the WebSocket protocol.
|
||||
//
|
||||
// The responseHeader is included in the response to the client's upgrade
|
||||
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
|
||||
// application negotiated subprotocol (Sec--Protocol).
|
||||
//
|
||||
// If the upgrade fails, then Upgrade replies to the client with an HTTP error
|
||||
// response and the return `Connection.Err()` is filled with that error.
|
||||
//
|
||||
// For a more high-level function use the `Handler()` and `OnConnecton` events.
|
||||
// This one does not starts the connection's writer and reader, so after your `On/OnMessage` events registration
|
||||
// the caller has to call the `Connection#Wait` function, otherwise the connection will be not handled.
|
||||
func (s *Server) Upgrade(ctx context.Context) Connection {
|
||||
conn, err := s.upgrader.Upgrade(ctx.ResponseWriter(), ctx.Request(), ctx.ResponseWriter().Header())
|
||||
if err != nil {
|
||||
ctx.Application().Logger().Warnf("websocket error: %v\n", err)
|
||||
ctx.StatusCode(503) // Status Service Unavailable
|
||||
return &connection{err: err}
|
||||
}
|
||||
|
||||
return s.handleConnection(ctx, conn)
|
||||
}
|
||||
|
||||
// wrapConnection wraps an underline connection to an iris websocket connection.
|
||||
// It does NOT starts its writer, reader and event mux, the caller is responsible for that.
|
||||
func (s *Server) handleConnection(ctx context.Context, websocketConn UnderlineConnection) *connection {
|
||||
// use the config's id generator (or the default) to create a websocket client/connection id
|
||||
cid := s.config.IDGenerator(ctx)
|
||||
// create the new connection
|
||||
@@ -179,22 +199,7 @@ func (s *Server) handleConnection(ctx context.Context, websocketConn UnderlineCo
|
||||
// join to itself
|
||||
s.Join(c.ID(), c.ID())
|
||||
|
||||
// NOTE TO ME: fire these first BEFORE startReader and startPinger
|
||||
// in order to set the events and any messages to send
|
||||
// the startPinger will send the OK to the client and only
|
||||
// then the client is able to send and receive from Server
|
||||
// when all things are ready and only then. DO NOT change this order.
|
||||
|
||||
// fire the on connection event callbacks, if any
|
||||
for i := range s.onConnectionListeners {
|
||||
s.onConnectionListeners[i](c)
|
||||
}
|
||||
|
||||
// start the ping
|
||||
c.startPinger()
|
||||
|
||||
// start the messages reader
|
||||
c.startReader()
|
||||
return c
|
||||
}
|
||||
|
||||
/* Notes:
|
||||
|
||||
Reference in New Issue
Block a user